爱猫的狗

拥抱变化

导航

Windows Forms Programming In C# 读书笔记 - 第三章 Dialogs

1。Handling OK and Cancel
    对于modal form ,如果 DialogResult 属性被开发者显式地设置了除了None以外的值,则该对话框会被自动关闭(会自动调用 Close() 方法)。
    如果想让用户在按 Enter 以及 Esc 时相当于按了 OK 和 Cancel 按钮(符合一般的操作习惯),要设置对话框的 AcceptButton 以及 CancelButton 属性(可以直接在相应Form的属性栏中设置,在 Misc 分类中)。

void InitializeComponent() {
    
    
this.AcceptButton = this.okButton;
    
this.CancelButton = this.cancelButton;
    
}


    一般来说,如果设置了AcceptButton 以及 CancelButton 属性,则这两个按钮的的envent handler 就不需要了。

   绝对要注意的是,需要手写类似如下的语句,写在Form的constructor中的 InitializeComponent() 后面:

        this.okButton.DialogResult = DialogResult.OK;
        this.cancelButton.DialogResult = DialogResult.Cancel;

不能写在 InitializeComponent() 中,因为该方法是 IDE 自动生成的。

2。对于Modeless Form Data

   Modeless Form 在关闭的时候怎么把相应的信息带回调用它的 Form 呢?答案就是 .Net 中的event

class PropertiesDialog : Form {
  
  
// 当 Accept 按钮被按下时候的 Event
  public event EventHandler Accept;

  
void acceptButton_Click(object sender, EventArgs e) {
    
// Accept 按钮的实践处理方法
    if( Accept != null ) Accept(this, EventArgs.Empty);
  }


  
void closeButton_Click(object sender, EventArgs e) {
    
this.Close();
  }

}

//以下代码在主窗口对应的cs文件

void showProperties_Click(object sender, EventArgs e) {
  PropertiesDialog dlg 
= new PropertiesDialog();
  dlg.Accept 
+= new EventHandler(Properties_Accept);
  dlg.Show();
}


// Client handles event from form to access accepted values
void Properties_Accept(object sender, EventArgs e) {
  PropertiesDialog dlg 
= (PropertiesDialog)sender;
  
this.Text = dlg.Text;
}




posted on 2005-02-27 11:14  anf  阅读(528)  评论(0编辑  收藏  举报