WPF 实现验证码控件

WPF开发者QQ群

此群已满340500857 ,请加新群458041663

       由于微信群人数太多入群请添加小编微信号

 yanjinhuawechatW_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

7460458e34931c4536632e98ba4b460b.png

扫一扫关注我们,

238d996ecdc7e4376fcd668526323477.gif

更多知识早知道!

c7230dbfbafefd5bf5d434eaae43c68c.gif

点击阅读原文可跳转至源代码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/290494.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

curl   liinux下http命令执行工具

安装cURLwget http://curl.haxx.se/download/curl-7.17.1.tar.gztar -zxf curl-7.17.1.tar.gz./configure --prefix/usr/local/curlmake & make installCurl是Linux下一个很强大的http命令行工具&#xff0c;其功能十分强大。1) 二话不说&#xff0c;先从这里开始吧&#x…

王道408数据结构——第二章 线性表

文章目录一、线性表的定义和基本操作线性表顺序表1.插入操作2.删除操作3.按值查找&#xff08;顺序查找&#xff09;二、单链表1. 头插法2. 尾插法3. 按序号查找4. 按值查找5. 插入结点6. 删除结点7. 求表长三、 双链表1. 插入2. 删除四、循环链表五、静态链表六、顺序表和链表…

C和指针之用拉托斯特尼筛方法(Eratosthenes)查找区间质素个数

1、问题 用拉托斯特尼筛方法(Eratosthenes)查找区间质素个数 2、代码实现 #include <stdio.h> #define LEN 10000 /***Eratosthenes-埃拉托斯特尼筛方法找质数,给出要筛数值的范围n,先用2去筛,2的倍数不是质数,* 再用下一个素数,也就是3筛,把3留下,把3的倍数不是…

Mysql数据库性能优化

2019独角兽企业重金招聘Python工程师标准>>> Mysql数据库性能优化&#xff0c;可以从下面三点入手&#xff1a; 数据库设计 SQL语句优化 架构优化 一.数据库设计优化 1.适度的违反范式&#xff0c;适度 遵循三大范式就会带来查询时经常需要join&#xff0c;导致…

BZOJ 2588: Spoj 10628. Count on a tree 树上跑主席树

2588: Spoj 10628. Count on a tree Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://www.lydsy.com/JudgeOnline/problem.php?id2588Description 给定一棵N个节点的树&#xff0c;每个点有一个权值&#xff0c;对于M个询问(u,v,k)&#xff0c;你需要回答u xor las…

session多服务器共享的方案梳理

因方便自己学习以此记录本文转自&#xff1a;http://www.cnblogs.com/wangtao_20/p/3395518.html#2846008session的存储了解以前是怎么做的&#xff0c;搞清楚了来龙去脉&#xff0c;才会明白进行共享背后的思想和出发点。我喜欢按照这样的方式来问(或者去搞清楚)&#xff1a;为…

4. 堪比JMeter的.Net压测工具 - Crank 进阶篇 - 认识wrk、wrk2

1. 前言上一篇文章我们了解了bombardier&#xff0c;并知道了bombardier.yml与开源项目bombardier的关系&#xff0c;接下来的文章我们了解一下wrk、wrk2&#xff0c;并对比一下它们与bombardier的关系2. 认识wrkwrk是一种现代 HTTP 基准测试工具&#xff0c;能够在单个多核 CP…

王道408数据结构——第三章 栈和队列

一、栈 栈&#xff08;Stack&#xff09;是只允许在一端进行插入或删除操作的线性表。 栈顶&#xff1a;线性表允许插入删除的那一端 栈底&#xff1a;固定的、不允许进行插入删除的另一端 栈的操作特性可以概括为后进先出&#xff08;LIFO&#xff09; n个不同的元素进栈&…

C和指针之const、#define、volatile

1、const 定义const 只读变量,具有不可变形 const int a = 100; 编译器通常不为普通Const只读变量分配存储空间, 而是将它们保存在符号表中, 这使得它成为一个编译期间的值,没有了存储与读内存操作,使用效率很高 #define M3 //宏常量const int N = 5; //此时并没有将…

dispatchTouchEvent onInterceptTouchEvent onTouchEvent区分

1. dispatchTouchEvent 是处理触摸事件分发,执行super.dispatchTouchEvent(ev)&#xff0c;事件向下分发。 2. onInterceptTouchEvent是ViewGroup提供的方法&#xff0c;默认返回false&#xff0c;返回true表示拦截。 3. onTouchEvent是View中提供的方法&#xff0c;ViewGroup也…

Avalonia跨平台入门第二十篇之语音播放问题

在前面分享的几篇中咱已经玩耍了Popup、ListBox多选、Grid动态分、RadioButton模板、控件的拖放效果、控件的置顶和置底、控件的锁定、自定义Window样式、动画效果、Expander控件、ListBox折叠列表、聊天窗口、ListBox图片消息、窗口抖动、语音发送、语音播放;今晚加个班来解决…

递归算法浅谈

递归算法 程序调用自身的编程技巧称为递归&#xff08; recursion&#xff09;。   一个过程或函数在其定义或说明中又直接或间接调用自身的一种方法&#xff0c;它通常把一个大型复杂的问题层层转化为一个与原问题类似的规模较小的问题来求解&#xff0c;递归策略仅仅需少量…

C和指针之实现strlen函数

1、问题 求字符串长度,实现strlen函数。 2、代码实现 #include <stdio.h> #include <assert.h>int get_strlen(char *str) {assert(NULL != str);return *str == \0 ? 0 : (1 + get_strlen(++str)); }int main() {char *str = "chenyu";char…

王道408数据结构——第四章 串(KMP算法)

一、串的定义和实现 字符串简称串&#xff0c;是由零个或多个字符组成的有限序列&#xff0c;一般记为S′a1a2⋅⋅⋅an′Sa_1a_2a_nS′a1​a2​⋅⋅⋅an′​&#xff0c;n称为串的长度。 串中任意多个连续字符组成的子序列称为该串的子串&#xff0c;相应的该串称为主串。某个…

ThoughtWorks技术雷达专区

作为一家服务于全球不同类型的IT专业服务公司&#xff0c;ThoughtWorks从未停止过对卓越技术的追求&#xff0c;为此&#xff0c;ThoughtWorks的全球技术委员会(TAB)会定期讨论技术战略&#xff0c;并将其绘制成一份能够体现技术趋势的雷达图&#xff0c;它相当于当下技术领域的…

腾讯视频VIP周卡深圳地区免费领!附非深圳免费领腾讯视频会员攻略

深圳今天开始&#xff0c;暂停了所有公共交通&#xff0c;小区开始封闭管理&#xff0c;大家都居家办公&#xff0c;腾讯官方今天给深圳地区用户免费发放7天腾讯视频VIP会员&#xff0c;居家期间&#xff0c;可以追剧了&#xff01;这是腾讯官方给深圳地区的抗疫福利&#xff0…

编译器与解释器

什么是编译器&#xff1f;什么事解释器&#xff1f; 编译器是女儿&#xff0c;解释器是儿子。为什么这么说呢&#xff1f; 引用文章 http://www.cnblogs.com/sword03/archive/2010/06/27/1766147.html 大概总结就是&#xff1a;妈给儿子和女儿打电话说&#xff1a;你们的老爸不…

SQL Server 权限的分类

SQL Server 的权限可以分三类 第一类 server 层面上的&#xff1a; select * from sys.fn_builtin_permissions(default) where class_desc like server; 第二类 database 层面&#xff1a; select * from sys.fn_builtin_permissions(default)    where class_desc like d…

C和指针之部分理解和编码总结

1、在C语言中,当一维数组作为函数参数的时候,编译器总是把它解析成一个指向成一个指向其首元素首地址的指针 这也就是为什么数组int a[10],a不能a++操作,而把a传递给函数的时候,可以作为指针a++操作的原因。 2、内存为0的地址处,也就是NULL地址处,一般定义指针变量的同时…

王道408数据结构——第五章 树与二叉树

文章目录一、树的基本概念树的性质二、二叉树满二叉树完全二叉树二叉排序树平衡二叉树二叉树的性质完全二叉树的性质三、二叉树的储存结构顺序储存链式存储四、树的储存方式双亲表示法孩子表示法孩子兄弟表示法&#xff08;二叉树表示法&#xff09;五、二叉树的遍历先序遍历&a…