2009-08-04 3 views
15

콤보 상자가 활성화되어있을 때 Windows 양식 콤보 상자에서 Enter 키를 캡처하려면 어떻게합니까?Windows 양식 콤보 상자에서 Enter 키를 캡처하는 방법

KeyDown 및 KeyPress를 수신하려고 시도했으며 하위 클래스를 만들고 ProcessDialogKey를 재정의했지만 아무것도 작동하지 않는 것 같습니다.

아이디어가 있으십니까?

/P

+1

AcceptButton이 정의되어 있습니까? –

답변

18

후크까지이 같은 방법에 KeyPress 이벤트는 :

protected void myCombo_OnKeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (e.KeyChar == 13) 
    { 
     MessageBox.Show("Enter pressed", "Attention");     
    } 
} 

내가 VS2008와 윈폼 응용 프로그램에서이 테스트를했는데 그것을 작동합니다.

작동하지 않는 경우 코드를 게시하십시오.

+0

나는 이미 그것을 시도했다. 작동하지 않습니다. 너 자신을 시험해보고. 그 이유는 내가 질문을 게시했습니다. – Presidenten

+0

나는 그것을 시도하고 그것은 잘 작동합니다. 코드 게시 ... –

+0

하나의 가능한 이유는 다른 이벤트 처리기가 먼저 입력을 포착하고 나머지 처리기가 작업을 중단한다는 것입니다. 예를 들어 메뉴 또는 양식 자체. – Petros

9

또는 altertatively 당신이에서 KeyDown 이벤트 후크 수 있습니다 경우

private void comboBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Enter) 
    { 
     MessageBox.Show("Enter pressed."); 
    } 
} 
+0

이 작업은 VS2010E, thx에서 가능합니다. :) –

17

당신이 당신의 양식 AcceptButton을 정의, 당신은에서 KeyDown /의 keyup/키 누름에 Enter 키를들을 수 없습니다.

는 확인하기 위해서는 FORM에 ProcessCmdKey를 오버라이드 (override) 할 필요가 : 당신이 콤보 상자에있는 경우 당신에게 메시지 상자를 줄 것이 예에서

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); 
    } 
} 

및 다른 모든 컨트롤에 대한 이전 작업 .

0

대화 상자에 양식 등록 정보의 AcceptButton으로 설정되어 있기 때문에 Enter 키를 사용하는 버튼이있을 수 있습니다.
그런 경우는 다음 컨트롤이 포커스를 잃을 일단 컨트롤이 다시 초기화 한 후 초점 가져옵니다 AcceptButton 속성을 설정 해제하여이 같은이 문제를 해결 있다면

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"); 
     } 
    } 

I (내 코드를, 단추 1은 동의 버튼입니다) 사람이 더 나은 솔루션이있는 경우 다음 내가 관심이있을 거라고 그래서가 설정에 약간의 해키 보인다 내 자신의 솔루션을 좋아하지 않는 인정해야 /를 AcceptButton 속성을 설정

1
private void comboBox1_KeyDown(object sender, EventArgs e) 
{ 
    if(e.KeyCode == Keys.Enter) 
    { 
     // Do something here... 
    } else Application.DoEvents(); 
} 
1

이 시도 :

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); 
} 
0
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로 설정하는 것을 잊지 마십시오.

관련 문제