WPF 实现验证码控件
WPF开发者QQ群
此群已满340500857 ,请加新群458041663
由于微信群人数太多入群请添加小编微信号
yanjinhuawechat 或 W_Feng_aiQ 邀请入群
需备注WPF开发者
01
—
代码如下
一、创建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>
02
—
效果预览
鸣谢素材提供者 - 屈越
源码地址如下
Github:https://github.com/WPFDevelopersOrg
Gitee:https://gitee.com/WPFDevelopersOrg
WPF开发者QQ群: 340500857 | 458041663
Github:https://github.com/WPFDevelopersOrg
出处:https://www.cnblogs.com/yanjinhua
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
转载请著名作者 出处 https://github.com/WPFDevelopersOrg
扫一扫关注我们,
更多知识早知道!
点击阅读原文可跳转至源代码
WPF 实现验证码控件相关推荐
- 看看这套WPF开源基础控件库:WPFDevelopers
此项目包含了 微信公众号 < WPF开发者> 日常开发分享,欢迎Star. 运行环境 Visual Studio 2019,dotNet Framework 4.0 SDK 欢迎关注微信公 ...
- WPF查找子控件和父控件方法
原文:WPF查找子控件和父控件方法 public List<T> GetChildObjects<T>(DependencyObject obj, string name) w ...
- WPF 动画显示控件
原文:WPF 动画显示控件 当我们要显示一个控件的时候,不仅仅要显示这个控件,还要有动画的效果. 主要用到了DoubleAnimation类. public static void ShowAnima ...
- WPF的Timer控件的使用
原文:WPF的Timer控件的使用 通过System.Threaing.Timer控件来实现"初始加载页面时为DataGrid的模版列赋初始值" System.Threaing.T ...
- Wpf使用Winform控件后Wpf元素被Winform控件遮盖问题的解决
Wpf使用Winform控件后Wpf元素被Winform控件遮盖问题的解决 参考文章: (1)Wpf使用Winform控件后Wpf元素被Winform控件遮盖问题的解决 (2)https://www. ...
- WPF之复杂形状控件
WPF之复杂形状控件 原文:WPF之复杂形状控件 有的时候想将一张图片变成一个按钮.当然这里不是单纯讲图片作为按钮的背景. 这两者是有区别的: 前者图片即按钮,比如你有一个空心的圆圈,当你点击中间空心 ...
- WPF 4 日历控件(Calendar)
WPF 4 日历控件(Calendar) 原文:WPF 4 日历控件(Calendar) 在之前我已经写过两篇关于WPF 4 任务栏(Taskbar)相关的特性.相信自从VS2010 Beta 版放出 ...
- WPF Calendar 日历控件 样式自定义
原文:WPF Calendar 日历控件 样式自定义 粗略的在代码上做了些注释 blend 生成出来的模版 有的时候 会生成 跟 vs ui界面不兼容的代码 会导致可视化设计界面 报错崩溃掉 但是确不 ...
- [ASP.NET 控件实作 Day28] 图形验证码控件
在网页上常把图形验证码应用在登入或贴文的页面中,因为图形验证码具有机器不易识别的特性,可以防止机器人程序恶意的存取网页.在本文中将实作一个图形验证码的服务器控件,透过简单的属性设定就可以轻易地在网页上 ...
最新文章
- js 正则匹配URL,网址,带端口,带query的
- 小程序商城选什么服务器,小程序商城到底用来干什么?
- HDU OJ 5437 Alisha’s Party 2015online A
- python break -else 语句
- ARM(IMX6U)裸机主频和时钟
- 【Python CheckiO 题解】Multicolored Lamp
- php等级证书,php银行开放平台接口1:php 对cer证书处理
- Vue3.x 推荐使用 mitt.js
- VRTK HTC手柄发出射线,瞬移,选择物体 VRTK和steamVR对应版本
- 网易蜗牛读书与微信读书竞品分析
- Windows出现“未连接到互联网代理服务器出现问题,或者地址有误。问题解决办法”
- Unity3D接入Android第三方SDK流程
- HW - VCN 介绍
- 介绍一种Android 平台 不需要获取imei imsi 无权限就能获取手机运营商的方法
- 一切发生的事,都是好事(19年总结)
- 一条狗的死亡,引发3亿网友愤怒!希望这条黑科技 “汪星人” 能从小培养人的爱心 | 钛空智慧星球推荐
- 11.14 尚品汇 day01 脚手架,路由命名,路由跳转,传参,props传参,重写push,replace
- 数学建模论文基本格式(转载)
- ios中导入第三方类库
- 查询无限级/三级分销的简单易用SQL