我有两个项目。一个称为Main,另一个称为UserAuth。除非用户通过UserAuth,否则我不想运行Main。我知道我的代码存在很多问题,这就是我寻求帮助的原因。我想要做的是从此LoginForm返回userAuthenticated。我无法弄清楚如何去做。我创建了一个public变量userAuthenticated,但我无法访问它。这是我的代码:
namespace UserAuth
{
public partial class LoginForm : Form
{
public bool userAuthenticated;
private int attempts = 0;
public bool LoginForm() // Error 'LoginForm': member names cannot be the same as their enclosing type UserAuth
{
InitializeComponent();
return (userAuthenticated);
}
private void btnLogin_Click(object sender, EventArgs e)
{ // authenticate user -- works fine }
被叫:
LoginForm lf = new LoginForm();
lf.Show();
任何帮助都将不胜感激。
答案 0 :(得分:4)
我会删除所有的全局变量,我只能使用模态对话框所期望的预定义模式。换句话说,我会通过Winforms设计器将btnLogin的属性DialogResult设置为DialogResult.Cancel,然后修改btnLogin_Click中的代码
// this is the form constructor, cannot return anything here
public LoginForm()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
// this method contains your logic to authenticate the user
// the method returns true if the user is ok or false if not
bool result = AuthenticateUser();
// If the user is authenticated close the login form setting OK
// as the return value
if(result)
this.DialogResult = DialogResult.OK;
// else the return from the form will be DialogResult.Cancel as
// set in the button's DialogResult property
}
现在调用登录表单的代码应该只是
using(LoginForm fLogin = new LoginForm())
{
if(DialogResult.OK == fLogin.ShowDialog())
{
MessageBox.Show("Login OK");
}
else
{
MessageBox.Show("Login failed");
}
}