用户名: 密码: 验证码: 注册           网站地图 高级搜索 RSS订阅 收藏本站
山东十七地市站长联盟信息: 济南 青岛 淄博 枣庄 东营 烟台 潍坊 济宁 泰安 威海 日照 莱芜 临沂 德州 聊城 滨州 菏泽      
您的位置:主页>网络编程>.Net编程>

用C#如何写一个简单的Login窗口

[ 来源: | 作者: | 更新日期:2007-10-11 19:30:39 | 评论 0 条 | 我要投稿 ]
最近,看到网上经常会问如何进行窗口跳转,大多数的问题都是牵扯到Login窗口。其实,在Visual Studio 6以来,比较正确的做法是判断Login窗口的返回值,然后决定是否打开主窗体,那么在C#中也是一样的。

  具体做法如下: 字串6

  首先,创建Login窗口,然后添加相应的输入框和按钮,设置窗口的AcceptButton为窗体的确认按钮,而CancelButton为窗体的取消按钮。例如: 字串2

this.AcceptButton = this.btnOK;
this.CancelButton = this.btnCancel;
  定义确定按钮以及取消按钮事件,如下:

字串2

private void btnOK_Click(object sender, System.EventArgs e)
  {
  // Here is to use fixed username and password
  // You can check username and password from DB
  if( txtUserName.Text == "Admin" && txtPassword.Text == "nopassword" )
  {
  // Save login user info
  uiLogin.UserName = txtUserName.Text;
  uiLogin.Password = txtPassword.Text;
  // Set dialog result with OK
  this.DialogResult = DialogResult.OK;
  }
  else
  {
  // Wrong username or password
  nLoginCount++;
  if( nLoginCount == MAX_LOGIN_COUNT )
  // Over 3 times
  this.DialogResult = DialogResult.Cancel;
  else
  {
  MessageBox.Show( "Invalid user name and password!" );
  txtUserName.Focus();
  }
  }
  }
  private void btnCancel_Click(object sender, System.EventArgs e)
  {
  // Set dialog result with Cancel 字串7
  this.DialogResult = DialogResult.Cancel;
  }
  然后,在Login窗体的Closing事件中,要进行处理,如下: 字串8

private void frmLogin_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  {
  // Check whether form is closed with dialog result
  if( this.DialogResult != DialogResult.Cancel &&
  this.DialogResult != DialogResult.OK )
  e.Cancel = true;
  }
  除此外,Login窗体一些辅助代码如下:

字串6

private int nLoginCount = 0;
  private const int MAX_LOGIN_COUNT = 3;
  private UserInfo uiLogin;
  public frmLogin( ref UserInfo ui )
  {
  //
  // Required for Windows Form Designer support
  //
  InitializeComponent();
  // Set login info to class member
  uiLogin = ui;
  }
  调用的时候,要修改程序的Main函数,如下: 字串8

/// 
  /// The main entry point for the application.
  /// 
  [STAThread]
  static void Main()
  {
  UserInfo ui = new UserInfo();
  frmLogin myLogin = new frmLogin( ref ui );
  if( myLogin.ShowDialog() == DialogResult.OK )
  {
  //Open your main form here
  MessageBox.Show( "Logged in successfully!" );
  }
  else
  {
  MessageBox.Show( "Failed to logged in!" );
  }
  }
  而附加的UserInfo类如下: 字串9

/// 
  /// User info class
  /// 
  public class UserInfo
  {
  private string strUserName;
  private string strPassword;
  public string UserName
  {
  get{ return strUserName;}
  set{ strUserName = value; }
  }
  public string Password
  {
  get{ return strPassword;}
  set{ strPassword = value;}
  }
  public UserInfo()
  {
  strUserName = "";
  strPassword = "";
  }
  } 字串3


Tags:窗口 简单 一个 如何 // private UserInfo 如下 /// 按钮
您的评论
用户名:新注册) 密码: 匿名评论 [所有评论]

·用户发表意见仅代表其个人意见,并且承担一切因发表内容引起的纠纷和责任
·本站管理人员有权在不通知用户的情况下删除不符合规定的评论信息或留做证据
·请客观的评价您所看到的资讯,提倡就事论事,杜绝漫骂和人身攻击等不文明行为