フックによるWindowsキーの無効化

説明:

WH_GETMESSAGEのフックによって、WM_USER+260というメッセージを遮断し、Windowsキー(およびCTRL+ESC)が押されたときにスタートメニューが表示されないようにする。

Form1上には、二つのボタンがある。Command1を押下するとWindowsキーが無効化され、次にCommand2を押下するとWindowsキーの無効化が取り消される。

本サンプルではフック用のDLLをCで作成してある。これをコンパイルしたものはhttp://tokyo.cool.ne.jp/masapico/HookDll.dllにある。

キーワード:

FindWindow, GetWindowThreadProcessId, LoadLibrary, GetProcAddress, SetWindowsHookEx, FreeLibrary, UnhookWindowsHookEx

サンプルコード:

'------------------------ Form1.frmのソース ------------------------

Dim hHook As Long

Private Sub Command1_Click()

    Dim pMsgHook As Long
    Dim hHookDll As Long
    Dim Path As String
    Dim hWnd As Long
    Dim ThreadId As Long

    Path = App.Path
    If Right(Path, 1) <> "\" Then Path = Path & "\"
    
    hWnd = FindWindow("Shell_TrayWnd", vbNullString)
    ThreadId = GetWindowThreadProcessId(hWnd, 0)
        
    hHookDll = LoadLibrary(Path & "hookdll.dll")
    pMsgHook = GetProcAddress(hHookDll, "MsgHook")
    hHook = SetWindowsHookEx(WH_GETMESSAGE, pMsgHook, hHookDll, ThreadId)
    FreeLibrary hHookDll

End Sub


Private Sub Command2_Click()
   
   UnhookWindowsHookEx hHook
 
End Sub

'------------------------ Module1.basのソース ------------------------
Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal DllName As String) As Long
Declare Function GetProcAddress Lib "kernel32" (ByVal hDll As Long, ByVal FuncName As String) As Long
Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" _
    (ByVal wh As Long, ByVal pFunc As Long, ByVal hHook As Long, ByVal ThreadId As Long) As Long
Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Declare Function FreeLibrary Lib "kernel32" (ByVal hDll As Long) As Long

Public Const WH_GETMESSAGE As Long = 3

Type POINT
    X As Long
    Y As Long
End Type

Declare Function GetWindowThreadProcessId Lib "user32" _(ByVal hWnd As Long, ByVal pProccessId As Long) As Long
Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
    (ByVal ClassName As String, ByVal WindowTitle As String) As Long



'------------------------ HookDll.cのソース ------------------------
#include <windows.h>

LRESULT CALLBACK MsgHook(int nCnode, WPARAM wParam, LPARAM lParam)
{
	MSG *pmsg;

	pmsg = (MSG *)lParam;
	if(pmsg->message == WM_USER + 260) pmsg->message = WM_NULL;

	return 0;
}

(original text:1999/05/27 更新)

本ドキュメントの内容は保証しません。本ドキュメントによって生じた結果について、一切の責任を負いません。