2012-01-02 29 views
0

我想讓Esc鍵撤消對文本框的任何更改,因爲它獲得焦點。在文本框中捕獲ESC

我有文字,但似乎無法弄清楚如何捕捉Esc的關鍵。 KeyUpKeyPressed似乎都不明白。

+1

請張貼您的代碼,並告訴我們,如果這是winforms,webform,WPF或其他東西。 – Oded 2012-01-02 23:17:48

+0

請參閱http://stackoverflow.com/questions/1798383/press-escape-key-to-call-method獲得相似的答案。有效處理OnKeyPress事件,然後檢查e.KeyCode(根據鍵盤的回答)。請張貼您當前的嘗試! – dash 2012-01-02 23:18:53

+2

當文本框顯示在對話框中時,它不起作用,Escape是設計用於取消對話框的快捷鍵。您可以從TextBox派生自己的類並重寫IsInputKey()。你不應該。 – 2012-01-03 02:40:32

回答

6

這應該工作。你如何處理這個事件?

private void textBox1_KeyDown(object sender, KeyEventArgs e) 
{   
    if (e.KeyCode == Keys.Escape) 
    { 
     MessageBox.Show("Escape Pressed"); 
    } 
} 

編輯在回覆評論 - 嘗試重寫ProcessCmdKey代替:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{ 
    if (keyData == Keys.Escape && myTextBox.Focused) 
    { 
     MessageBox.Show("Escape Pressed"); 
    } 

    return base.ProcessCmdKey(ref msg, keyData); 
} 
+0

它沒有。當按下ESC鍵時,它永遠不會進入此功能(它適用於「普通」鍵) – baruch 2012-01-02 23:27:08

+1

重寫「ProcessCmdKey」是否工作? http://msdn.microsoft.com/en-us/library/system.windows.forms.control.processcmdkey.aspx在使用'ProcessCmdKey'之前,請嘗試第一個方法並確保KeyPreview設置爲'true'。例如,在你的表單構造函數中,添加'this.KeyPreview = true; ' – keyboardP 2012-01-02 23:33:17

+0

這將影響表格。我只想捕獲這個文本框。 – baruch 2012-01-02 23:36:54

1

這是你在找什麼?

string origStr = String.Empty; 
    private void txtOrig_Enter(object sender, EventArgs e) 
    { 
     origStr = txtOrig.Text; 
    } 

    private void txtOrig_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (e.KeyChar == Convert.ToChar(Keys.Escape)) 
     { 
      txtOrig.Text = origStr; 
     } 
    } 
+0

不可以。正如我所解釋的那樣,ESC鍵從不觸發KeyPress事件 – baruch 2012-01-03 07:48:49

相關問題