2014-10-13 3 views
0

두 개의 텍스트 상자가 있으며 각기 다른 키 누르기 이벤트가 첨부되어 있습니다.하나의 키 이벤트를 포커스가있는 컨트롤에 연결하십시오.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if(e.KeyChar == '\r') 
    { 
     e.Handled = true; 
     // some other stuff 
    } 
} 
private void textBox2_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if(e.KeyChar == '\r') 
    { 
     e.Handled = true; 
     // some other stuff 
    } 
} 

키 누르기 이벤트를 포커스가있는 텍스트 상자에 동적으로 연결하는 방법이 있습니까?

편집 :

뭔가 같은 :

void KeyPress(object sender, KeyPressEventArgs e) 
{ 
    foreach(Control c in this) 
    { 
     if(c == TextBox && c.Focused) 
     { 
      if(e.KeyChar == '\r') 
      { 
       // do something 
      } 
     } 
    } 
} 
+0

foreach는 (이에서 제어 c)에 그게 ^^ –

+0

Naaa, 그것은 그냥하지 않는 절대 의사 코드 ^^ – betaFlux

+0

내 대답을 봐,이 방법은 할 수있다 –

답변

2

당신은이 작업을 수행 할 수 있습니다

textBox1.KeyPress += new KeyPressEventHandler(textBox_KeyPress); 
textBox2.KeyPress += new KeyPressEventHandler(textBox_KeyPress); 

private void textBox_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if(e.KeyChar == '\r') 
    { 
     e.Handled = true; 
     // some other stuff 
     Console.WriteLine(((TextBox)sender).Name); //actual textbox name 
    } 
} 
+0

이것은 갈 방법입니다. 감사! – betaFlux

+0

당신을 환영합니다;) –