이 문서의 Microsoft Visual C# 버전에 대한 내용은 를 참조하십시오.
요약
이 문서에서는 스레드와 후크 프로시저에 특정한 후크를 설정하는 방법을 설명합니다. 이 문서에서는 마우스 후크를 예제로 사용합니다.
후크를 사용하여 특정 종류의 이벤트를 모니터링할 수 있습니다. 이러한 이벤트를 동일한 데스크톱에서 호출 스레드 역할을 하는 모든 스레드 또는 특정 스레드와 연결할 수 있습니다.
추가 정보
마우스 후크 설정
후크를 설정하려면 User32.dll 파일에서 SetWindowsHookEx 함수를 호출합니다. 이 함수에서는 후크와 연결된 후크 체인에 응용 프로그램 정의 후크 프로시저를 설치합니다.
마우스 후크를 설정하고 마우스 이벤트를 모니터링하려면 다음과 같이 하십시오.
-
Microsoft Visual Studio .NET을 시작합니다.
-
파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 누릅니다.
-
새 프로젝트 대화 상자의 프로젝트 형식에서 Visual Basic 프로젝트를 누릅니다. 그런 다음 템플릿 아래에서 Windows 응용 프로그램을 누릅니다.
-
이름 입력란에 ThreadSpecificMouseHook를 입력합니다. 기본적으로 Form1이라는 폼이 만들어집니다.
-
Form1.vb 파일의 시작 부분에 다음 코드를 붙여 넣습니다.
Imports System.Runtime.InteropServices
Public Delegate Function CallBack( _
ByVal nCode As Integer, _
ByVal wParam As IntPtr, _
ByVal lParam As IntPtr) As Integer -
Form1 클래스에서 다음 코드를 붙여 넣습니다.
'Declare the mouse hook constant.
'For other hook types, obtain these values from Winuser.h in Microsoft SDK.
Dim WH_MOUSE As Integer = 7
Shared hHook As Integer = 0
'Keep the reference so that the delegate is not garbage collected.
Private hookproc As CallBack
'Import for the SetWindowsHookEx function.
<DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
Public Overloads Shared Function SetWindowsHookEx _
(ByVal idHook As Integer, ByVal HookProc As CallBack, _
ByVal hInstance As IntPtr, ByVal wParam As Integer) As Integer
End Function
'Import for the CallNextHookEx function.
<DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
Public Overloads Shared Function CallNextHookEx _
(ByVal idHook As Integer, ByVal nCode As Integer, _
ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
End Function
'Import for the UnhookWindowsHookEx function.
<DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
Public Overloads Shared Function UnhookWindowsHookEx _
(ByVal idHook As Integer) As Boolean
End Function
'Point structure declaration.
<StructLayout(LayoutKind.Sequential)> Public Structure Point
Public x As Integer
Public y As Integer
End Structure
'MouseHookStruct structure declaration.
<StructLayout(LayoutKind.Sequential)> Public Structure MouseHookStruct
Public pt As Point
Public hwnd As Integer
Public wHitTestCode As Integer
Public dwExtraInfo As Integer
End Structure -
폼에 단추를 추가합니다. 그런 다음 button1_click 프로시저에 다음 코드를 붙여 넣습니다.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If hHook.Equals(0) Then
hookproc = AddressOf MouseHookProc
hHook = SetWindowsHookEx(WH_MOUSE, _
hookproc, _
IntPtr.Zero, _
AppDomain.CurrentDomain.GetCurrentThreadId())
If hHook.Equals(0) Then
MsgBox("SetWindowsHookEx Failed")
Return
Else
Button1.Text = "UnHook Windows Hook"
End If
Else
Dim ret As Boolean = UnhookWindowsHookEx(hHook)
If ret.Equals(False) Then
MsgBox("UnhookWindowsHookEx Failed")
Return
Else
hHook = 0
Button1.Text = "Set Windows Hook"
Me.Text = "Mouse Hook"
End If
End If
End Sub -
Form1 클래스에서 MouseHookProc 함수에 대한 다음 코드를 붙여 넣습니다.
Public Shared Function MouseHookProc( _
ByVal nCode As Integer, _
ByVal wParam As IntPtr, _
ByVal lParam As IntPtr) As Integer
Dim MyMouseHookStruct As New MouseHookStruct()
Dim ret As Integer
If (nCode < 0) Then
Return CallNextHookEx(hHook, nCode, wParam, lParam)
End If
MyMouseHookStruct = CType(Marshal.PtrToStructure(lParam, MyMouseHookStruct.GetType()), MouseHookStruct)
Dim tempForm As Form
tempForm = Form.ActiveForm()
Dim strCaption As String
strCaption = "x = " & MyMouseHookStruct.pt.x & " y = " & MyMouseHookStruct.pt.y
tempForm.Text = strCaption
Return CallNextHookEx(hHook, nCode, wParam, lParam)
End Function -
F5 키를 눌러 프로젝트를 실행합니다. 폼에서 단추를 눌러 후크를 설정합니다. 마우스 포인터가 폼에서 이동할 때 포인터 좌표가 폼 캡션 표시줄에 나타납니다.
-
단추를 다시 눌러서 후크를 제거합니다.
글로벌 후크는 .NET Framework에서 지원되지 않음
Microsoft .NET Framework에서는 글로벌 후크를 구현할 수 없습니다. 글로벌 후크를 설치하려면 일관성 있고 유효한 함수를 호출해야 하는 다른 프로세스에 기본 DLL을 삽입하는 기본 DLL 내보내기가 후크에 있어야 합니다. 이 동작에는 DLL 내보내기가 필요합니다. .NET Framework에서는 DLL 내보내기를 지원하지 않습니다. 이러한 함수 포인터는 동적으로 만들어지는 프록시이기 때문에 관리 코드에는 함수 포인터에 대해 일관성 있는 값이라는 개념이 없습니다.
참조
후크에 대한 자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하십시오.
(영문)
Microsoft 제품 관련 기술 전문가들과 온라인으로 정보를 교환하시려면 에 참여하시기 바랍니다.