2012-06-14

C# Get hWnd by mouse position

참고: http://www.codeproject.com/Articles/16481/NET-Object-Spy-and-InvokeRemote

지난 번, WH_MOUSE에 대해 Global hook을 해서 hwnd를 구하려고 했으나, WH_MOUSE는 Global hook이 지원되지 않는다는 글을 올렸다.
위 참고의 소스에서 마우스 좌표만으로 hwnd를 구하는 방법이 있어, 글을 남긴다.

WindowFromPoint로 hwnd를 구할 수 있다.
 // 마우스 좌표를 주면 hwnd를 return한다.
[DllImport("user32.dll")]
protected static extern IntPtr WindowFromPoint(int x , int y);



        #region 프로세스 정보 클래스
        class processInfobyMousePosition
        {
            #region public 멤버
            public int _mousex, _mousey;
            public IntPtr _hwnd;
            public string _processname;
            public string _windowtext;
            public string _classname;
            #endregion

            #region public method
            public void SetPositon(int x, int y)
            {
                if (x >= 0 & y >= 0)
                {
                    _mousex = x; _mousey = y;
                    _hwnd = GetHandle();
                    _processname = GetProcessName(_hwnd);
                    _windowtext = GetWindowText(_hwnd);
                    _classname = GetClassName(_hwnd);
                }
            }
            #endregion

            #region private method
            private string GetProcessName(IntPtr hWnd)
            {
                int pid;
                GetWindowThreadProcessId(hWnd, out pid);
                Process proc = Process.GetProcessById(pid);
                return proc.MainModule.ModuleName;
            }
            private IntPtr GetHandle()
            {
                return WindowFromPoint(_mousex, _mousey);
            }
            private string GetWindowText(IntPtr hWnd)
            {
                StringBuilder text = new StringBuilder(256);
                if (GetWindowText(hWnd, text, text.Capacity) > 0)
                {
                    return text.ToString();
                }
                return String.Empty;
            }
            private string GetClassName(IntPtr hWnd)
            {
                StringBuilder className = new StringBuilder(100);
                if (GetClassName(hWnd, className, className.Capacity) > 0)
                {
                    return className.ToString();
                }
                return String.Empty;
            }
            #endregion

            #region dll import
            [DllImport("user32.dll")]
            protected static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
            [DllImport("user32.dll")]
            protected static extern IntPtr WindowFromPoint(int x , int y);
            [DllImport("user32.dll")]
            protected static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
            [DllImport("user32.dll")]
            protected static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
            #endregion
        }
        #endregion
// 

댓글 없음:

댓글 쓰기