在 C# 中面临密码表单问题
本文关键字:密码 表单 问题 | 更新日期: 2023-09-27 18:35:05
我有两种不同的表单,一种表单专用于密码输入,如果密码正确,请打开一个对话框,用于从PC加载文件,如果错误,则会出现一个消息框,指出密码错误。问题是,如果程序已启动并且我单击按钮并输入正确的密码并成功加载文件。但是,如果我再次按下按钮输入密码并通过顶部的X手动关闭弹出窗口,则可以访问对话框窗口。我无法知道如何阻止这种情况。
我的代码如下
表格 1:
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;
using System.IO;
using System.Windows;
using System.Threading;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
formpopup popup = new formpopup();
popup.ShowDialog();
if (formpopup.j == 1)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
}
}
}
}
另一种形式的密码是:
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 WindowsFormsApplication2
{
public partial class formpopup : Form
{
public formpopup()
{
InitializeComponent();
}
public static int j = 0;
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
if (a == "1234")
{
j = 1;
textBox1.Text = string.Empty;
this.Close();
}
else
{
j = 0;
textBox1.Text = string.Empty;
this.Close();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
是的,我也尝试使用形式。Dispose() 命令,但没有任何反应。
您的解决方案想要重新设计:"j"
到底意味着什么?
// Make the class name readable, use upper case (FormPopup instead of formpopup):
public partial class FormPopup : Form {
public FormPopup() {
InitializeComponent();
}
//TODO: rename the button as well as the textbox
private void button1_Click(object sender, EventArgs e) {
if (textBox1.Text == "1234")
DialogResult = System.Windows.Forms.DialogResult.OK;
else
DialogResult = System.Windows.Forms.DialogResult.Cancel;
// In case form was open as non-dialog
Close();
}
}
....
public partial class Form1 : Form {
...
private void button1_Click(object sender, EventArgs e) {
// Wrap IDisposable into using
using (FormPopup dialog = new FormPopup()) {
if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
return; // wrong password
}
// Wrap IDisposable into using
using (OpenFileDialog fileDialog = new OpenFileDialog()) {
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
//TODO: put relevant code here
}
}
}
}
问题是你的j是静态的。使其非静态,以便引用表单的实例
public int j = 0;
然后你应该以类似的方式引用你的表格
if (popup.j == 1)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
}