下面是我參照着C++代碼寫的C#代碼
一、首先聲明Hook的類型
public enum HookType
{
Keyboard = 2,//鍵盤操作
};
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();//得到當前的線程ID
static extern int GetDlgItem(IntPtr hDlg, int nIDDlgItem);//得到Dialog窗口的子項
static extern int SetDlgItemTextA(IntPtr hDlg, int nIDDlgItem, string lpString);//設置Dialog窗口子項的文本
static extern void UnhookWindowsHookEx(IntPtr handle);//解掉掛鉤
static extern IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr
static extern IntPtr CallNextHookEx(IntPtr handle, int code, IntPtr wparam, IntPtr lparam);//進行下一個掛鉤,如果有的話
static IntPtr _nextHookPtr;
static HookProc myProc = new HookProc(MyHookProc);//must be global, or it will be Collected by GC, then no callback
delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam);
static IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam)
{
IntPtr hChildWnd;// msgbox is "child"
// window handle is wParam
if (code == 5)//HCBT_ACTIVATE = 5
{
// set window handles of messagebox
hChildWnd = wparam;
//to get the text of yes button
{
result = SetDlgItemTextA(hChildWnd, 6, Properties.Resources.YES);//在Project.Resources裏自定義文本
}
if (GetDlgItem(hChildWnd, 7) != 0)//IDNO = 7
{
result = SetDlgItemTextA(hChildWnd, 7, Properties.Resources.NO);
}
}
else
{
CallNextHookEx(_nextHookPtr, code, wparam, lparam);// otherwise, continue with any possible chained hooks
}
return IntPtr.Zero;//返回,讓後面的程序處理該消息
五、提供給外部調用的Hook方法,如在Form_Load時SetHook,Form_Closing時UnHook.
public static void SetHook()
{
if (_nextHookPtr != IntPtr.Zero)//Hooked already
{
return;
}
}
{
if (_nextHookPtr != IntPtr.Zero)
{
UnhookWindowsHookEx(_nextHookPtr);
}
}
目的達到了,看代碼就知道,這樣不僅可以讓button的文本可以根據語言改變,文本的內容也可以自定義。
事實證明搶劫的收穫是誘人的,但是風險成本也是很高的,
1.對於掛鉤Hook技術,我們還不是很熟悉,比如什麼死後SetHook(),什麼時候UnHook()就是值得考慮的一個問題,你也可以在程序啓動就
2.回調函數要判斷消息號,所有的Form在Activate的時候都是code = 5,但是我們只有在彈出MessageBox的時候設置Button的文本。所以如果我
至少我們知道了,這個問題有解決方案。