2011-01-23 5 views
3

이것은 C# Get a control's position on a form의 반대 질문입니다.C# 양식의 특정 위치에서 컨트롤 가져 오기

양식 내의 Point 위치가 주어지면 그 위치에서 사용자가 볼 수있는 컨트롤을 어떻게 알 수 있습니까?

현재 HelpRequested 양식 이벤트를 사용하여 MSDN: MessageBox.Show Method과 같이 별도의 도움말 양식을 표시하고 있습니다.

MSDN 예제에서 sender 이벤트는 도움말 메시지를 확인하는 데 사용되지만 sender은 항상 내 양식의 컨트롤이 아니라 양식입니다.

양식 내에서 특정 컨트롤을 얻으려면 HelpEventArgs.MousePos을 사용하고 싶습니다.

답변

4

당신은 양식의 Control.GetChildAtPoint 방법을 사용할 수 있습니다. 여러 단계를 거쳐야하는 경우이 작업을 반복적으로 수행해야 할 수 있습니다. this answer도 참조하십시오.

+1

좋은 시작, 감사합니다. HelpEventArgs.MousePos는 마우스 포인터의 화면 좌표를 제공하는 반면 GetChildAtPoint는 "컨트롤의 클라이언트 영역의 왼쪽 위 모퉁이를 기준으로"입니다. 따라서 재귀 적으로 특정 컨트롤을 검색하기 전에 일부 변환을 수행하여 사용 가능한 지점을 가져와야합니다. –

2

당신은 Control.GetChildAtPoint를 사용할 수 있습니다

var controlAtPoint = theForm.GetChildAtPoint(thePosition); 
0

이 코드는 Control.GetChildAtPoint와 Control.PointToClient를 모두 사용하여 사용자가 클릭 한 지점에서 정의 된 태그를 사용하여 컨트롤을 재귀 적으로 검색합니다.

private void Form1_HelpRequested(object sender, HelpEventArgs hlpevent) 
{ 
    // Existing example code goes here. 

    // Use the sender parameter to identify the context of the Help request. 
    // The parameter must be cast to the Control type to get the Tag property. 
    Control senderControl = sender as Control; 

    //Recursively search below the sender control for the first control with a Tag defined to use as the help message. 
    Control controlWithTag = senderControl; 
    do 
    { 
     Point clientPoint = controlWithTag.PointToClient(hlpevent.MousePos); 
     controlWithTag = controlWithTag.GetChildAtPoint(clientPoint); 

    } while (controlWithTag != null && string.IsNullOrEmpty(controlWithTag.Tag as string)); 

    // Existing example code goes here.  
} 
관련 문제