WPF-21:WPF實現仿安卓的圖案密碼鍵盤(初級)

來源:互聯網
上載者:User

希望大家有這方面好的代碼給提供下,謝謝了!

    想用C#做一個和手機上一樣的圖形密碼鍵盤,貌似這方面資料比較少,雖然winphone手機上也有但是網上也沒有這方面的代碼。只好用常規的思維去實現一下,當然是比較簡單的,希望各路高手能給一些好的建議,這篇文章算是拋磚引玉吧,用WPF實現。

思路如下:
    使用常用控制項從最簡單的圖案繪製,然後放在相應的控制項上,利用滑鼠的Move事件,判斷滑鼠滑過哪些控制項,然後將控制項上的對應密碼的數字收集,最終形成密碼。
具體實現:
    工程名:TestPicturePassword
一般常見的圖案密碼按鍵都是圓形的,所以利用重繪事件畫一個圓形。

 /// <summary>    /// 按鍵形狀類    /// </summary>    public class KeyBorder:Border    {        public Brush SelfBacground        {            get { return (Brush)GetValue(SelfBacgroundProperty); }            set             {                 SetValue(SelfBacgroundProperty, value);                this.InvalidateVisual();            }        }        public static readonly DependencyProperty SelfBacgroundProperty =           DependencyProperty.Register("SelfBacground", typeof(Brush), typeof(KeyBorder), new UIPropertyMetadata());        /// <summary>        /// 使繪製地區為自訂形狀,這裡是圓形        /// </summary>        /// <param name="dc"></param>        protected override void OnRender(System.Windows.Media.DrawingContext dc)        {            base.OnRender(dc);            //畫矩形的            //SolidColorBrush mySolidColorBrush = new SolidColorBrush();            //mySolidColorBrush.Color = Colors.LimeGreen;            //Pen myPen = new Pen(Brushes.Blue, 10);            //Rect myRect = new Rect(0, 0, 500, 500);            //dc.DrawRectangle(mySolidColorBrush, myPen, myRect);            //畫圓形            EllipseGeometry ellipse = new EllipseGeometry(new Point(40, 40), 30, 30);//piont中的參數最好要設定屬性進行外部設定            ellipse.RadiusX = 30;            ellipse.RadiusY = 30;            RectangleGeometry rect = new RectangleGeometry(new Rect(50, 50, 50, 20), 5, 5);            GeometryGroup group = new GeometryGroup();            group.FillRule = FillRule.EvenOdd;            group.Children.Add(ellipse);            //group.Children.Add(rect);            dc.DrawGeometry(SelfBacground, new Pen(Brushes.Green, 2), group);        }    }

再將這個圓形放在另一個容器中,將容器控制項的背景設定為透明。

<UserControl x:Class="TestPicturePassword.KeyButton"             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:TestPicturePassword"             mc:Ignorable="d"  Background="Transparent"             BorderThickness="0">    <Grid>        <local:KeyBorder x:Name="ellipseBorder" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>    </Grid></UserControl>

 

  /// <summary>    /// KeyButton.xaml 的互動邏輯    /// </summary>    public partial class KeyButton : UserControl    {        public Brush SelfBacground        {            get { return (Brush)GetValue(SelfBacgroundProperty); }            set             {                SetValue(SelfBacgroundProperty, value);                this.ellipseBorder.SelfBacground = value;            }        }        public static readonly DependencyProperty SelfBacgroundProperty =           DependencyProperty.Register("SelfBacground", typeof(Brush), typeof(UserControl), new UIPropertyMetadata());        public KeyButton()        {            InitializeComponent();        }    }

最終將按鍵按要求排布,

<UserControl x:Class="TestPicturePassword.PatternPasswordKeyboard"             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:TestPicturePassword"             mc:Ignorable="d"              d:DesignHeight="300" d:DesignWidth="300">    <Grid HorizontalAlignment="Center" Name="grid1" VerticalAlignment="Center"              Background="Transparent">        <Grid.Resources>            <!--鍵盤按鈕的樣式-->            <Style x:Key="PasswordBorderStyle" TargetType="local:KeyButton">                <Setter Property="Background" Value="Transparent"/>                <Setter Property="SelfBacground" Value="Gray"/>                <Setter Property="Width" Value="80" />                <Setter Property="Height" Value="80" />                <Setter Property="Margin" Value="10"/>                <Setter Property="HorizontalAlignment" Value="Stretch"/>                <Setter Property="VerticalAlignment" Value="Stretch"/>                <EventSetter Event="Mouse.MouseMove" Handler="BorderMouseMove"/>            </Style>        </Grid.Resources>            <Grid.RowDefinitions>                <RowDefinition Height="auto"/>                <RowDefinition Height="auto"/>                <RowDefinition Height="auto"/>            </Grid.RowDefinitions>            <Grid.ColumnDefinitions>                <ColumnDefinition Width="auto" />                <ColumnDefinition Width="auto" />                <ColumnDefinition Width="auto" />            </Grid.ColumnDefinitions>            <local:KeyButton Grid.Row="0" Grid.Column="0"  x:Name="border1"  Style="{StaticResource PasswordBorderStyle}" Tag="1" />            <local:KeyButton Grid.Row="0" Grid.Column="1"  x:Name="border2"  Style="{StaticResource PasswordBorderStyle}" Tag="2" />            <local:KeyButton Grid.Row="0" Grid.Column="2"  x:Name="border3"  Style="{StaticResource PasswordBorderStyle}" Tag="3" />            <local:KeyButton Grid.Row="1" Grid.Column="0"  x:Name="border4"  Style="{StaticResource PasswordBorderStyle}" Tag="4" />            <local:KeyButton Grid.Row="1" Grid.Column="1"  x:Name="border5"  Style="{StaticResource PasswordBorderStyle}" Tag="5" />            <local:KeyButton Grid.Row="1" Grid.Column="2"  x:Name="border6"  Style="{StaticResource PasswordBorderStyle}" Tag="6" />            <local:KeyButton Grid.Row="2" Grid.Column="0"  x:Name="border7"  Style="{StaticResource PasswordBorderStyle}" Tag="7" />            <local:KeyButton Grid.Row="2" Grid.Column="1"  x:Name="border8"  Style="{StaticResource PasswordBorderStyle}" Tag="8" />            <local:KeyButton Grid.Row="2" Grid.Column="2"  x:Name="border9"  Style="{StaticResource PasswordBorderStyle}" Tag="9" />    </Grid></UserControl>

後台代碼,在這裡實現密碼收集。
 

  /// <summary>    /// PatternPasswordKeyboard.xaml 的互動邏輯    /// </summary>    public partial class PatternPasswordKeyboard : UserControl    {        public string password = string.Empty;//最終密碼        private bool isMouseDonw = false;//控制只有滑鼠按下的滑動才有效        private List<KeyButton> keyButtons = new List<KeyButton>();//密碼所在的控制項        public PatternPasswordKeyboard()        {            InitializeComponent();            this.MouseUp += new MouseButtonEventHandler(MainWindow_MouseUp);            this.MouseDown += new MouseButtonEventHandler(MainWindow_MouseDown);        }        /// <summary>        /// 重設        /// </summary>        internal void PatternPasswordKeyboard_ResetPassword()        {            this.password = string.Empty;            foreach (KeyButton item in keyButtons)            {                item.SelfBacground = new SolidColorBrush(Colors.Transparent);            }        }        void MainWindow_MouseDown(object sender, MouseButtonEventArgs e)        {            isMouseDonw = true;        }        void MainWindow_MouseUp(object sender, MouseButtonEventArgs e)        {            isMouseDonw = false;        }        private void BorderMouseMove(object sender, MouseEventArgs e)        {            if (!isMouseDonw)            {                return;            }            KeyButton border = sender as KeyButton;            if (border == null)            {                return;            }            string key = border.Tag.ToString();            if (string.IsNullOrEmpty(key))            {                return;            }            if (!password.Contains(key))            {                password += key;            }            border.SelfBacground = new SolidColorBrush(Colors.Blue);            keyButtons.Add(border);        }    }

測試代碼:

<Window x:Class="TestPicturePassword.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:local="clr-namespace:TestPicturePassword"        Title="MainWindow" xmlns:my="clr-namespace:TestPicturePassword">    <Grid>                <Grid.RowDefinitions>            <RowDefinition Height="*"/>            <RowDefinition Height="auto"/>            <RowDefinition Height="auto"/>        </Grid.RowDefinitions>                <local:PatternPasswordKeyboard Grid.Row="0" x:Name="pkeyboard"/>                <StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">            <TextBlock Text="您輸入的密碼是:" VerticalAlignment="Center" FontSize="20" FontFamily="Microsoft YaHei" Margin="0,0,20,0"/>            <TextBox Height="50" HorizontalAlignment="Left"  Name="textBox1" VerticalAlignment="Top" Width="291" Margin="0,0,50,0"/>            <Button Content="重 置" Height="50" HorizontalAlignment="Left" Name="button1" VerticalAlignment="Top" Width="110" Click="button1_Click" />        </StackPanel>    </Grid></Window>

   /// <summary>    /// MainWindow.xaml 的互動邏輯    /// </summary>    public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            this.MouseUp += new MouseButtonEventHandler(MainWindow_MouseUp);        }        void MainWindow_MouseUp(object sender, MouseButtonEventArgs e)        {            this.textBox1.Text = pkeyboard.password;        }       /// <summary>       /// 重設       /// </summary>       /// <param name="sender"></param>       /// <param name="e"></param>        private void button1_Click(object sender, RoutedEventArgs e)        {            this.pkeyboard.PatternPasswordKeyboard_ResetPassword();        }    }

代碼下載:http://download.csdn.net/detail/yysyangyangyangshan/5724829

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.