2008-10-29 2 views
9

.NET UserControl (FFX 3.5)이 있습니다. 이 컨트롤에는 Panel, 두 개의 레이블, 두 개의 TextBoxes 및 또 다른 사용자 정의 컨트롤과 같은 여러 자식 컨트롤이 포함되어 있습니다. 기본 컨트롤의 아무 곳이나 오른쪽 클릭을 처리하고 싶습니다. 따라서 하위 컨트롤 (또는 Panel의 경우 자식)을 마우스 오른쪽 버튼으로 클릭하십시오. 누군가가 새로운 컨트롤에 대한 핸들러에서 와이어 링하지 않고도 컨트롤을 변경하면 유지 보수가 가능하도록 예제를 작성하고 싶습니다.처리 a 양식의 모든 컨트롤을 클릭하십시오.

먼저 WndProc을 재정의하려고 시도했지만, 의심 스러울 때 폼의 클릭에 대한 메시지 만 가져오고 자식은 직접받지 못합니다.

foreach (Control c in this.Controls) 
    { 
    c.MouseClick += new MouseEventHandler(
     delegate(object sender, MouseEventArgs e) 
     { 
     // handle the click here 
     }); 
    } 

이 이제 이벤트를 지원하는 제어하지만, 라벨의 클릭 수를 얻을, 예를 들어, 여전히 아무것도하지 않는 : 반 해킹으로, 나는 InitializeComponent를 한 후 다음과 같은 추가했다. 이것을 간과 할 수있는 간단한 방법이 있습니까? 레이블이 서브 컨트롤에있는 경우

답변

15

당신은 재귀 적으로이 작업을 수행해야 할 것 :

void initControlsRecursive(ControlCollection coll) 
{ 
    foreach (Control c in coll) 
    { 
     c.MouseClick += (sender, e) => {/* handle the click here */}); 
     initControlsRecursive(c.Controls); 
    } 
} 

/* ... */ 
initControlsRecursive(Form.Controls); 
+0

그래서 내가 나무 숲을 볼 수 없었던 것은 당연합니다. 감사. – ctacke

0

사용자 정의 UserControl을에 모든 컨트롤을 마우스 오른쪽 버튼으로 클릭에 대한 MouseClick과 이벤트를 처리하려면

public class MyClass : UserControl 
{ 
    public MyClass() 
    { 
     InitializeComponent(); 

     MouseClick += ControlOnMouseClick; 
     if (HasChildren) 
      AddOnMouseClickHandlerRecursive(Controls); 
    } 

    private void AddOnMouseClickHandlerRecursive(IEnumerable controls) 
    { 
     foreach (Control control in controls) 
     { 
      control.MouseClick += ControlOnMouseClick; 

      if (control.HasChildren) 
       AddOnMouseClickHandlerRecursive(control.Controls); 
     } 
    } 

    private void ControlOnMouseClick(object sender, MouseEventArgs args) 
    { 
     if (args.Button != MouseButtons.Right) 
      return; 

     var contextMenu = new ContextMenu(new[] { new MenuItem("Copy", OnCopyClick) }); 
     contextMenu.Show((Control)sender, new Point(args.X, args.Y)); 
    } 

    private void OnCopyClick(object sender, EventArgs eventArgs) 
    { 
     MessageBox.Show("Copy menu item was clicked."); 
    } 
} 
관련 문제