我有两种不同的形式,一种形式专用于密码输入,如果密码正确,打开一个对话框,用于从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)
{
}
}
}
是的,我也试过使用form.Dispose()命令,但没有任何反应。
答案 0 :(得分:1)
您的解决方案需要重新设计:地球上的"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
}
}
}
}
答案 1 :(得分:0)
问题是您的 j 是静态的。使其成为非静态的,因此它将引用表单的实例
public int j = 0;
然后你应该以类似的方式参考你的表格
if (popup.j == 1)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
}