-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathctrl-ja.cs
91 lines (73 loc) · 2.89 KB
/
ctrl-ja.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace CtrlJa {
public static class Program {
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x0101;
private const int WM_IME_CONTROL = 0x0283;
private const int IMC_SETOPENSTATUS = 0x0006;
private static HookProc hookProc = HookCallback;
private static IntPtr hookId = IntPtr.Zero;
private static Keys keydownKey;
public static void Main() {
Console.CancelKeyPress += new ConsoleCancelEventHandler(Exit);
hookId = SetHook(hookProc);
Application.Run();
UnhookWindowsHookEx(hookId);
}
private static void Exit (object sender, ConsoleCancelEventArgs args) {
Application.Exit();
}
private static IntPtr SetHook(HookProc hookProc) {
IntPtr moduleHandle = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
return SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, moduleHandle, 0);
}
private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
private static void SwitchIme(int status) {
IntPtr hFgWnd = GetForegroundWindow();
SendMessageA(ImmGetDefaultIMEWnd(hFgWnd), WM_IME_CONTROL, IMC_SETOPENSTATUS, status);
}
private static void HandleKeyMessage(int nCode, IntPtr wParam, IntPtr lParam) {
if (nCode < 0) {
return;
}
if (wParam == (IntPtr)WM_KEYDOWN) {
int vkCode = Marshal.ReadInt32(lParam);
keydownKey = (Keys)vkCode;
} else if (wParam == (IntPtr)WM_KEYUP) {
int vkCode = Marshal.ReadInt32(lParam);
Keys keyupKey = (Keys)vkCode;
if (keydownKey != keyupKey) {
return;
}
if (keyupKey == Keys.LControlKey) {
SwitchIme(0);
} else if (keyupKey == Keys.RControlKey) {
SwitchIme(1);
}
}
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
HandleKeyMessage(nCode, wParam, lParam);
return CallNextHookEx(hookId, nCode, wParam, lParam);
}
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll")]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern IntPtr SendMessageA(IntPtr hWnd, int wMsg, int wParam, int lParam);
[DllImport("imm32.dll")]
private static extern IntPtr ImmGetDefaultIMEWnd(IntPtr hWnd);
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
}