2012-08-27 28 views
0

我正在C#項目中實現一個WinForms表單。
我的表單是MDI表單的孩子。
我的表單包含一個用戶控件。
我的用戶控件包含一些按鈕,包括驗證按鈕和取消按鈕。處理按鍵事件+ WinForms +驗證+取消

我要實現以下邏輯:

  • 當我的形式是活躍,用戶按下回車鍵,然後我想自動發射驗證按鈕點擊事件。
  • 當我的表單處於活動狀態並且用戶按下了轉義鍵時,我想讓取消按鈕點擊事件被自動觸發。

如果我的驗證,我的取消按鈕在用戶控件不包括那麼我可能會設置我的窗體的AcceptButton和CancelButton屬性。

+0

父窗體使用FindForm(),然後將其設置爲AcceptButton和CancelButton屬性。 – Arthur

回答

2

以下是我根據評論亞瑟給我的第一篇小費寫在我的用戶控件的Load事件處理程序的代碼:你可以得到控制的onload

// Get the container form. 
form = this.FindForm(); 

// Simulate a click on the validation button 
// when the ENTER key is pressed from the container form. 
form.AcceptButton = this.cmdValider; 

// Simulate a click on the cancel button 
// when the ESC key is pressed from the container form. 
form.CancelButton = this.cmdAnnulerEffacer; 
1
  1. 從屬性設置true的KeyPreview屬性;

  2. 添加keyDownEvent到窗體

  3. 在窗體的keyDownEvent,包括代碼

代碼

if(e.KeyValue==13)// When Enter Key is Pressed 
{ 
    // Last line is performing click. Other lines are making sure 
    // that user is not writing in a Text box 
     Control ct = userControl1 as Control; 
     ContainerControl cc = ct as ContainerControl; 
     if (!(cc.ActiveControl is TextBox)) 
      validationButton.PerformClick(); // Code line to performClick 
} 

if(e.KeyValue==27) // When Escape Key is Pressed 
{ 
    // Last line is performing click. Other lines are making sure 
    // that user is not writing in a Text box 
     Control ct = userControl1 as Control; 
     ContainerControl cc = ct as ContainerControl; 
     if (!(cc.ActiveControl is TextBox)) 
      cancelButton.PerformClick(); // Code line to performClick 
} 
以下行

validationButton或cancelButton是的名稱您按鈕,我只是假設。你可能有不同的。如果你有不同,使用你的名字而不是這兩個。

+0

如果有任何問題需要更新,請執行任何說明。 – Sami

+0

我跟隨了亞瑟給我的博文發表的評論。由於某種原因,我沒有遵循您的建議。如果用戶在文本框中輸入內容,然後按下回車鍵,那麼我必須執行測試,以便不調用validationButton.PerformClick。 – user1139666

+0

好的。對不起,我無法得到你從問題陳述中提到的情況。你的問題解決了嗎? – Sami