C#中利用Handle的操作

C#中利用Handle的操作

 

1.我新建了个窗体,窗体中放个Label,这个Label用来显示窗体的句柄。

2.拖个Timer控件到窗体中,设置属性Enable=true

3.代码里添加名字空间引用

  using System.Runtime.InteropServices;

  加入获得Handle的API

[DllImport("user32.dll")]

internal static extern IntPtr WindowFromPoint(Point Point);

加入获得鼠标焦点的API

[DllImport("user32.dll")]

internal static extern bool GetCursorPos(out Point lpPoint);

4.写Timer的Tick事件,获取Handle

  private void timer1_Tick(object sender, EventArgs e)

  {

            Point p;

            if (GetCursorPos(out p))

            {

                IntPtr hwndCurWindow = WindowFromPoint(p);

                lblhandle.Text = hwndCurWindow.ToString();

            }

  }

5.执行它,晃动你的鼠标,当你的鼠标在各个窗体间切换的时候,label一直在变,这个就是获得的句柄。

6.有了句柄又怎么样呢,我也不知道获得了句柄想干嘛。我的机器上有两个翻译软件,金山词霸和有道。有一个不能用的话也没有关系吧。我获得了有道窗体的句柄“B09FC”,我把它转成16进制的了,这样:hwndCurWindow.ToString("X");  于是我判断当句柄等于“B09FC”时,我就关掉窗体,我还要加入个关窗体的API:

  [DllImport("user32.dll")]

   public static extern bool CloseWindow(IntPtr hWnd);

然后我判断

  if (hwndCurWindow.ToString("X") == "B09FC")

  {

          CloseWindow(hwndCurWindow);

  }

执行它,这时当我打开有道词典的时候,我的鼠标一放上去,窗体就关掉。

我把它改成了一个Windows服务,让它在后台执行,好了,我再也不能使用有道了。

 

这是winform的代码

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

using System.Runtime.InteropServices;

 

namespace HandleShow

{

    public partial class Form1 : Form

    {

        [DllImport("user32.dll")]

        internal static extern IntPtr WindowFromPoint(Point Point);

        [DllImport("user32.dll")]

        internal static extern bool GetCursorPos(out Point lpPoint);

        [DllImport("user32.dll")]

        public static extern bool CloseWindow(IntPtr hWnd);

 

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void timer1_Tick(object sender, EventArgs e)

        {

            Point p;

            if (GetCursorPos(out p))

            {

                IntPtr hwndCurWindow = WindowFromPoint(p);

                lblhandle.Text = hwndCurWindow.ToString();

                if (hwndCurWindow.ToString("") == "332106")

                {

                    CloseWindow(hwndCurWindow);

                }

 

            }

 

        }

    }

}

 

闲来无事,复习下API。网上搜来的,我只能说太强大了

http://d.download.csdn.net/down/948047/yuz_yuz

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值