keyhook class
public class KeyHook
{
[DllImport("user32.dll")] static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc callback, IntPtr hInstance, uint threadId);
[DllImport("user32.dll")] static extern bool UnhookWindowsHookEx(IntPtr hInstance);
[DllImport("user32.dll")] static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, int wParam, IntPtr lParam);
[DllImport("kernel32.dll")] static extern IntPtr LoadLibrary(string lpFileName);
public static event EventHandler<Keys> keypressed;
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
const int WH_KEYBOARD_LL = 13;
const int WM_KEYDOWN = 0x100;
private static LowLevelKeyboardProc _proc = hookProc;
private static IntPtr hhook = IntPtr.Zero;
public static void SetHook()
{
try
{
IntPtr hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, hInstance, 0);
}
catch(Exception ex)
{
ClsReviewMgr.Ins.clsLogCtrl.WriteLog("KeyHook", $"SetHook : {ex.ToString()}", VOLib.FunctionalGroup.Log.ClsLogData.LOG_LEVEL.DAY);
}
}
public static void UnHook()
{
try
{
UnhookWindowsHookEx(hhook);
}
catch(Exception ex)
{
ClsReviewMgr.Ins.clsLogCtrl.WriteLog("KeyHook", $"UnHook : {ex.ToString()}", VOLib.FunctionalGroup.Log.ClsLogData.LOG_LEVEL.DAY);
}
}
public static IntPtr hookProc(int code, IntPtr wParam, IntPtr lParam)
{
try
{
if (code >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
Keys key = (Keys)vkCode;
keypressed?.Invoke(null, key);
}
}
catch(Exception ex)
{
ClsReviewMgr.Ins.clsLogCtrl.WriteLog("KeyHook", $"hookProc : {ex.ToString()}", VOLib.FunctionalGroup.Log.ClsLogData.LOG_LEVEL.DAY);
}
return CallNextHookEx(hhook, code, (int)wParam, lParam);
}
}
해당클래스 사용하는곳
public void start()
{
KeyHook.SetHook();
KeyHook.keypressed += KeyHook_keypressed;
}
private void KeyHook_keypressed(object sender, Keys e)
{
MessageBox.Show(e.ToString());
}
'[ Program ] > C#' 카테고리의 다른 글
[c#] 현재값과 가장 작으면서 근접하는 5의 배수 가져오기 (1) | 2022.11.11 |
---|---|
[c#] Nlog 사용법 (0) | 2022.09.23 |
네트워크 연결확인방법 (0) | 2022.03.20 |
반복문도는동안 컨트롤텍스트 바꾸기(현재까지 실행된내용 라벨에 업데이트) (0) | 2015.07.22 |
c# 크로스쓰레딩 - 다른쓰레드의 컨트롤 값변경 (0) | 2015.07.22 |
댓글