C#:根据鼠标位置获取窗口句柄,名字等

本文介绍了如何使用C#语言结合Windows API来获取鼠标坐标,并通过获取该坐标下的窗口句柄来显示窗口名称。通过演示代码实现,详细解释了如何调用API函数如GetCursorPos、WindowFromPoint、GetWindowText和GetClassName来完成这一任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<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());

        }
    }
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值