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。網上搜來的,我只能說太強大了