基于WPF实现验证码控件
作者:驚鏵 发布时间:2021-08-15 21:44:36
标签:WPF,验证码,控件
代码如下
一、创建CheckCode.xaml代码如下
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:WPFDevelopers.Controls">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Basic/ControlBasic.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type controls:CheckCode}" BasedOn="{StaticResource ControlBasicStyle}">
<Setter Property="Background" Value="{x:Null}"/>
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="40"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:CheckCode}">
<Image x:Name="PART_Image" Stretch="Fill" Source="{TemplateBinding ImageSource}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
二、CheckCode.cs代码如下
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WPFDevelopers.Controls
{
[TemplatePart(Name = ImageTemplateName, Type = typeof(Image))]
public class CheckCode : Control
{
private const string ImageTemplateName = "PART_Image";
private Image _image;
private Size _size = new Size(70, 23);
private const string strCode = "abcdefhkmnprstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(CheckCode),new PropertyMetadata(null));
/// <summary>
/// 随机生成的验证码
/// </summary>
public ImageSource ImageSource
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
/// <summary>
/// 字体颜色
/// </summary>
public Brush SizeColor
{
get { return (Brush)GetValue(SizeColorProperty); }
set { SetValue(SizeColorProperty, value); }
}
public static readonly DependencyProperty SizeColorProperty =
DependencyProperty.Register("SizeColor", typeof(Brush), typeof(CheckCode), new PropertyMetadata(DrawingContextHelper.Brush));
public CheckCode()
{
this.Loaded += CheckCode_Loaded;
}
private void CheckCode_Loaded(object sender, RoutedEventArgs e)
{
ImageSource = CreateCheckCodeImage(CreateCode(4), (int)this.ActualWidth, (int)this.ActualHeight);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_image = GetTemplateChild(ImageTemplateName) as Image;
if (_image != null)
_image.PreviewMouseDown += _image_PreviewMouseDown;
}
private void _image_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (!IsLoaded)
return;
ImageSource = CreateCheckCodeImage(CreateCode(4), (int)this.ActualWidth, (int)this.ActualHeight);
}
private string CreateCode(int strLength)
{
var _charArray = strCode.ToCharArray();
var randomCode = "";
int temp = -1;
Random rand = new Random(Guid.NewGuid().GetHashCode());
for (int i = 0; i < strLength; i++)
{
if (temp != -1)
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
int t = rand.Next(strCode.Length - 1);
if (!string.IsNullOrWhiteSpace(randomCode))
{
while (randomCode.ToLower().Contains(_charArray[t].ToString().ToLower()))
t = rand.Next(strCode.Length - 1);
}
if (temp == t)
return CreateCode(strLength);
temp = t;
randomCode += _charArray[t];
}
return randomCode;
}
private ImageSource CreateCheckCodeImage(string checkCode, int width, int height)
{
if (string.IsNullOrWhiteSpace(checkCode))
return null;
if (width <= 0 || height <= 0)
return null;
var drawingVisual = new DrawingVisual();
var random = new Random(Guid.NewGuid().GetHashCode());
using (DrawingContext dc = drawingVisual.RenderOpen())
{
dc.DrawRectangle(Brushes.White, new Pen(SizeColor, 1), new Rect(_size));
var formattedText = DrawingContextHelper.GetFormattedText(checkCode,color:SizeColor, flowDirection: FlowDirection.LeftToRight,textSize:20, fontWeight: FontWeights.Bold);
dc.DrawText(formattedText, new Point((_size.Width - formattedText.Width) / 2, (_size.Height - formattedText.Height) / 2));
for (int i = 0; i < 10; i++)
{
int x1 = random.Next(width - 1);
int y1 = random.Next(height - 1);
int x2 = random.Next(width - 1);
int y2 = random.Next(height - 1);
dc.DrawGeometry(Brushes.Silver, new Pen(Brushes.Silver, 0.5D), new LineGeometry(new Point(x1, y1), new Point(x2, y2)));
}
for (int i = 0; i < 100; i++)
{
int x = random.Next(width - 1);
int y = random.Next(height - 1);
SolidColorBrush c = new SolidColorBrush(Color.FromRgb((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255)));
dc.DrawGeometry(c, new Pen(c, 1D), new LineGeometry(new Point(x - 0.5, y - 0.5), new Point(x + 0.5, y + 0.5)));
}
dc.Close();
}
var renderBitmap = new RenderTargetBitmap(70, 23, 96, 96, PixelFormats.Pbgra32);
renderBitmap.Render(drawingVisual);
return BitmapFrame.Create(renderBitmap);
}
}
}
三、新建CheckCodeExample.cs代码如下
<UserControl x:Class="WPFDevelopers.Samples.ExampleViews.CheckCodeExample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"
xmlns:wpfdev="https://github.com/WPFDevelopersOrg/WPFDevelopers"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UniformGrid Rows="2" Columns="2">
<wpfdev:CheckCode SizeColor="LimeGreen"/>
<wpfdev:CheckCode SizeColor="Red"/>
<wpfdev:CheckCode SizeColor="DodgerBlue"/>
<wpfdev:CheckCode SizeColor="HotPink"/>
</UniformGrid>
</UserControl>
效果预览
源码地址如下
Github:https://github.com/WPFDevelopersOrg
Gitee:https://gitee.com/WPFDevelopersOrg
来源:https://mp.weixin.qq.com/s/4h6QZJZbloCAfGnIrCpJVQ
0
投稿
猜你喜欢
- 学C#的原因其实挺简单的,因为一直对游戏挺感兴趣,查了下比较流行的游戏引擎Unity的主要开发语言是C#,所以就决定从C#入手,学学面向对象
- schedule的四种用法schedule(task,time)task-所安排的任务 time-执行任务的时间作用:在时间等于
- BeanUtils.copyProperties忽略空值使用spring开发的人,对这行代码肯定不陌生,常用于DTO、VO、PO之间的复制。
- 本文实例为大家分享了Struts2框架拦截 器实例的示例代码,供大家参考,具体内容如下在看拦截 器的小例子的前我们先来看看sturts2的原
- 实例如下:package com.huad.luck;import java.util.ArrayList;import java.util
- Unity脚本自动添加头部注释就是创建.cs文件时自动添加作者名,创建时间,文件名等看示例,我们在Unity的project面板下先创建一个
- “读多写少”是大部分项目的一个特点。例如“购物”,总是看的人
- 一.mybatis的配置1.1 添加相应的jar包在lib文件夹下面添加mybatis的核心jar包以及依赖的jar包同在lib文件夹下面加
- 一、了解Spring自动装配的方式采用传统的XML方式配置Bean组件的关键代码如下所示<bean id="userMapp
- 我们在使用一些开源调度系统(比如:elastic-job等)的时候,对于任务的执行时间通常都是有规律性的,可能是每隔半小时执行一次,或者每天
- AOP是Spring中的面向切面的编程,这里简单感受一下如何在xml文件中配置一个切面。如上图所示,配置一个切面的主要思路有以下几个步骤。1
- java 中设计模式(值对象)的实例详解应用场景:在Java开发时,需要来回交换大量的数据,比如要为方法传入参数,也要获取方法的返回值,该如
- 1 简介之前我们在文章《K8ssandra入门-详细记录在Linux上部署K8ssandra到Kubernetes》成功地在Ubuntu上安
- springboot 启动找不到主类利用eclipse的maven插件,清理了了一下springboot的项目,结果再启动就找报找不到主类的
- @RequestBody部分属性丢失问题描述JavaBean实现public class VerifyNewFriendApplyReq i
- 最近在做代码优化时学习和研究了下JAVA多线程的使用,看了菜鸟们的见解后做了下总结。1、继承Thread类实现多线程继承Thread类的方法
- maven3 安装:安装 Maven 之前要求先确定你的 JDK 已经安装配置完成。Maven是 Apache 下的一个项目,目前最新版本是
- java 归并排序的实例详解归并排序 归并排序,指的是将两个已经排序
- 实验目的在C#和Rest/Restful以及其它的Web服务交互过程中,大量使用到JSON传递数据,如何快捷的转化C#对象到JSON和转化J
- 一、DataSource首先大家要清楚DataSource属于MyBatis三层架构设计的基础层 然后我们来看看具体的实现。在数据持久层中