C#:根據鼠標位置獲取窗口句柄,名字等

<pre name="code" class="csharp">using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace Test
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]

        [StructLayout(LayoutKind.Sequential)]//定義與API相兼容結構體,實際上是一種內存轉換
        public struct POINTAPI
        {
            public int X;
            public int Y;
        }

        [DllImport("user32.dll", EntryPoint = "GetCursorPos")]//獲取鼠標座標
        public static extern int GetCursorPos(
            ref POINTAPI lpPoint
        );

        [DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//指定座標處窗體句柄
        public static extern int WindowFromPoint(
            int xPoint,
            int yPoint
        );

        [DllImport("user32.dll", EntryPoint = "GetWindowText")]
        public static extern int GetWindowText(
            int hWnd,
            StringBuilder lpString,
            int nMaxCount
        );

        [DllImport("user32.dll", EntryPoint = "GetClassName")]
        public static extern int GetClassName(
            int hWnd,
            StringBuilder lpString,
            int nMaxCont
        );

        static void Main()
        {
            POINTAPI point = new POINTAPI();//必須用與之相兼容的結構體,類也可以
            //add some wait time
            Thread.Sleep(8000);
            GetCursorPos(ref point);//獲取當前鼠標座標

            int hwnd = WindowFromPoint(point.X, point.Y);//獲取指定座標處窗口的句柄
            StringBuilder name = new StringBuilder(256);
               GetWindowText(hwnd, name, 256);
               MessageBox.Show(name.ToString());
            GetClassName(hwnd, name, 256);
            MessageBox.Show(name.ToString());

        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章