C#设计登录窗体可以分为以下几步:
-
在Visual Studio中创建一个Windows Form应用程序,并在窗体上放置相应的控件(如Label、TextBox、Button等)
-
设计好登录窗体的样式和布局,并设置相应的控件属性,如字体、颜色、大小等。
-
在代码中添加相应的事件处理程序,如Button的Click事件,用于处理登录操作。
-
在登录操作中,需要验证输入的用户名和密码是否正确。可以将用户名和密码保存在数据库中,并在登录时通过查询数据库进行验证。
-
如果验证成功,则打开主窗体;如果验证失败,则弹出错误提示框。
-
在窗体关闭时,需要释放资源并退出程序。
下面是一个简单的登录窗体设计示例:
public partial class FrmLogin : Form
{
public FrmLogin()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UserBll ub = new UserBll();
if (ub.userLogin(txtUserName.Text,txtPassword.Text)!=null)
{
FrmMain fm = new FrmMain();
fm.Show();
this.Hide();
}
else
{
MessageBox.Show("账号或者密码错误,请重新输入。");
}
}
private string userLogin()
{
//1创建连接
/*SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=123456;database=hism;");
try
{
//2打开连接
conn.Open();
//创建命令
string sqlstr="select * from tbuser where user_name=@username and pwd=@password";
SqlCommand cmd = new SqlCommand(sqlstr,conn);
SqlParameter uparam = new SqlParameter("@username",txtUserName.Text);
SqlParameter pwdParam = new SqlParameter("@password",txtPassword.Text);
cmd.Parameters.Add(uparam);
cmd.Parameters.Add(pwdParam);
//执行命令
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
if (ds.Tables.Count < 1)
{
return null;
}
else if(ds.Tables[0].Rows.Count>0)
{
return ds.Tables[0].Rows[0]["user_name"].ToString();
}
else
{
return null;
}
}
catch (Exception ex)
{
}*/
return null;
}
private void txtPassword_KeyDown(object sender, KeyEventArgs e)
{
//MessageBox.Show("你按下了按键:"+e.KeyCode+" "+e.KeyValue);
if (e.KeyCode == Keys.Enter)
{
this.button1.PerformClick();
//button1_Click(sender, e);
}
}
private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
//e.Cancel = true;
}
private void notifyIcon1_Click(object sender, EventArgs e)
{
this.notifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
this.notifyIcon1.BalloonTipText = "我发的笑给你,你都没有收到吗?";
this.notifyIcon1.BalloonTipTitle = "新消息";
this.notifyIcon1.ShowBalloonTip(10);
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
上面的代码中,btnLogin_Click事件处理程序中先获取输入框中的用户名和密码,然后调用CheckLogin方法进行验证。如果验证成功,就打开主窗体并关闭登录窗体;如果验证失败,就弹出错误提示框。CheckLogin方法中可以查询数据库来验证用户名和密码的正确性。