當組合框處於活動狀態時,如何捕獲窗口組合框中的回車鍵?如何捕獲窗口組合框中的回車鍵
我試着聆聽KeyDown和KeyPress,我創建了一個子類並重寫了ProcessDialogKey,但似乎沒有任何工作。
任何想法?
/P
當組合框處於活動狀態時,如何捕獲窗口組合框中的回車鍵?如何捕獲窗口組合框中的回車鍵
我試着聆聽KeyDown和KeyPress,我創建了一個子類並重寫了ProcessDialogKey,但似乎沒有任何工作。
任何想法?
/P
掛鉤KeyPress事件的方法是這樣的:
protected void myCombo_OnKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
MessageBox.Show("Enter pressed", "Attention");
}
}
我在VS2008與WinForms應用程序測試這和它的作品。
如果它不適合你,請發佈你的代碼。
我已經試過了。這是行不通的。試試你的自我,看看。 這就是爲什麼我發佈的問題。 – Presidenten 2009-08-04 10:30:17
我已經嘗試過了,它工作得很好。發佈代碼... – 2009-08-04 10:32:43
或altertatively你可以掛鉤KeyDown事件:
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter pressed.");
}
}
如果你在表單上定義的AcceptButton,你可以不聽輸入的KeyDown/KEYUP /按鍵響應鍵。
爲了檢查這一點,你需要重寫ProcessCmdKey表格:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if ((this.ActiveControl == myComboBox) && (keyData == Keys.Return)) {
MessageBox.Show("Combo Enter");
return true;
} else {
return base.ProcessCmdKey(ref msg, keyData);
}
}
在這個例子中,會給你消息框,如果你是在組合框中,並像以前一樣適用於所有其他控件。
這可能是因爲您的對話框中有一個按鈕,它正在使用回車鍵,因爲它被設置爲表單屬性中的AcceptButton。
如果是這樣的話,那麼你通過取消當控件獲得焦點將重新回來,一旦控件失去焦點的AcceptButton物業解決這個問題是這樣的(在我的代碼中,將Button1是接受按鈕)
private void comboBox1_Enter(object sender, EventArgs e)
{
this.AcceptButton = null;
}
private void comboBox1_Leave(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
MessageBox.Show("Hello");
}
}
我不得不承認,因爲它似乎有點哈克給未設置不喜歡我自己的解決方案/設置的AcceptButton屬性,因此,如果任何人有一個更好的解決方案,然後我很想
private void comboBox1_KeyDown(object sender, EventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
// Do something here...
} else Application.DoEvents();
}
試試這個:
protected override bool ProcessCmdKey(ref Message msg, Keys k)
{
if (k == Keys.Enter || k == Keys.Return)
{
this.Text = null;
return true;
}
return base.ProcessCmdKey(ref msg, k);
}
protected void Form_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13) // or Key.Enter or Key.Return
{
MessageBox.Show("Enter pressed", "KeyPress Event");
}
}
不要忘記在表單上將KeyPreview設置爲true。
您是否定義了AcceptButton? – 2009-08-04 10:56:21