场景
在Winform上添加了一些按钮,但是不想让按钮随意被点击,点击按钮后会提示你输入密码。
输入正确密码才能执行相应的逻辑。
实现效果如下:
注:
博客:
BADAO_LIUMANG_QIZHI的博客_博客 关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
1、在主窗体之外再添加一个窗体,用来做输入密码提示框。
2、设计窗体布局如下
并且修改其代码为
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace mysqldatabak
{
public partial class PassForm : Form
{
private string password = "123456";
public PassForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (this.textBox_password.Text.Trim().Equals(this.password))
{
this.DialogResult = DialogResult.OK;
}
else
{
this.DialogResult = DialogResult.Cancel;
}
}
}
}
其中button1是确定按钮,在确定按钮的点击事件中验证密码是否正确,从而决定窗体的返回结果。
3、在主窗体的按钮的点击事件中
private void button5_Click(object sender, EventArgs e)
{
PassForm passForm = new PassForm();
passForm.ShowDialog();
if (passForm.DialogResult == DialogResult.OK)
{
MessageBox.Show("OK");
}
else {
MessageBox.Show("no");
}
}
显示上面的窗体并根据窗体的返回结果执行不同的逻辑,只有当窗体返回OK时密码验证正确。