using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; // 오토키 (AutoKey) — 키보드 키를 자동으로 반복 입력하는 윈도우 프로그램 // https://funsoft.co.kr/autokey/ // // 인터넷 접속·레지스트리 사용 없음. 설정은 exe 와 같은 폴더의 autokey.ini 에만 저장한다. // // 빌드: // C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:winexe /optimize+ // /out:AutoKey.exe /r:System.Windows.Forms.dll /r:System.Drawing.dll AutoKey.cs namespace AutoKey { internal static class Native { public const int WH_KEYBOARD_LL = 13; public const int WM_KEYDOWN = 0x0100; public const int WM_KEYUP = 0x0101; public const int WM_SYSKEYDOWN = 0x0104; public const int WM_SYSKEYUP = 0x0105; public const uint LLKHF_INJECTED = 0x00000010; // 우리가 SendInput 으로 만든 키 입력을 후킹에서 걸러내기 위한 표식 public static readonly IntPtr SELF_TAG = new IntPtr(0x4155544B); // "AUTK" public const uint INPUT_KEYBOARD = 1; public const uint KEYEVENTF_EXTENDEDKEY = 0x0001; public const uint KEYEVENTF_KEYUP = 0x0002; public const uint KEYEVENTF_SCANCODE = 0x0008; public const uint MAPVK_VK_TO_VSC = 0; [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } // INPUT 의 크기는 공용체 중 가장 큰 MOUSEINPUT 기준이어야 한다. // KEYBDINPUT 만 넣으면 64비트에서 크기가 달라져 SendInput 이 아무것도 보내지 않는다. [StructLayout(LayoutKind.Explicit)] public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; } [StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public INPUTUNION u; } [StructLayout(LayoutKind.Sequential)] public struct KBDLLHOOKSTRUCT { public uint vkCode; public uint scanCode; public uint flags; public uint time; public IntPtr dwExtraInfo; } public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize); [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint uCode, uint uMapType); [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vKey); } // 조합키 비트 internal static class Mod { public const int Ctrl = 1, Shift = 2, Alt = 4; } // 키 순서의 한 단계: 키 + 조합키 + 이 단계 뒤에 기다릴 시간 internal sealed class Step { public Keys Key; public int Mods; public int WaitMs; public Step(Keys key, int mods, int waitMs) { Key = key; Mods = mods; WaitMs = waitMs; } } public class MainForm : Form { private const int MAX_STEPS = 10; private const int TAP_MS = 30; // '누르기(탭)' 일 때 누르고 있는 시간 (게임이 한 프레임 안에 놓치지 않을 만큼) // ---- 설정 컨트롤 ---- private RadioButton rdoSingle; private RadioButton rdoSeq; private TextBox txtKey; private Button btnKey; private CheckBox chkCtrl, chkShift, chkAlt; private ListBox lstSeq; private Button btnAdd, btnDel, btnUp, btnDown, btnClear; private NumericUpDown numStepWait; private ComboBox cboPress; private NumericUpDown numHold; private NumericUpDown numInterval; private Label lblCps; private NumericUpDown numJitter; private NumericUpDown numRepeat; private ComboBox cboMethod; private TextBox txtHotkey; private Button btnSetHotkey; private Label lblMsg; private CheckBox chkTopMost; private Button btnToggle; private Label lblStatus; private Label lblCount; // ---- 상태 ---- private IntPtr hookId = IntPtr.Zero; private Native.LowLevelKeyboardProc hookProc; // GC 방지용 필드 private Keys hotkey = Keys.F7; // 오토 마우스(F6)와 같이 켜 둘 수 있게 기본값은 F7 private bool hotkeyHeld = false; // 키를 누르고 있을 때 자동 반복으로 여러 번 토글되지 않게 private Keys singleKey = Keys.Space; private readonly List steps = new List(); // 0 = 캡처 안 함, 1 = 단일 키, 2 = 순서에 추가, 3 = 시작/정지 키 private const int CAP_NONE = 0, CAP_SINGLE = 1, CAP_STEP = 2, CAP_HOTKEY = 3; private int capturing = CAP_NONE; private volatile bool running = false; private volatile int generation = 0; // Start 할 때마다 증가 private Thread worker; private long cycleCount = 0; private readonly Random rnd = new Random(); private System.Windows.Forms.Timer uiTimer; private bool loading = false; // 지금 눌려 있는(뗌을 아직 안 보낸) 키. 창을 닫을 때 남김없이 떼기 위해 기록한다. private readonly Dictionary downKeys = new Dictionary(); private volatile bool useScanCodes = true; private readonly string configPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "autokey.ini"); public MainForm() { BuildUi(); loading = true; LoadConfig(); loading = false; RefreshKeyText(); RefreshSeqList(-1); UpdateCps(); UpdateModeEnabled(); UpdateHotkeyText(); UpdateStatus(); hookProc = HookCallback; InstallHook(); uiTimer = new System.Windows.Forms.Timer(); uiTimer.Interval = 100; uiTimer.Tick += delegate { lblCount.Text = "반복 수: " + Interlocked.Read(ref cycleCount).ToString("N0"); }; uiTimer.Start(); } // ===================================================================== // 화면 구성 // ===================================================================== private void BuildUi() { Text = "오토키"; FormBorderStyle = FormBorderStyle.FixedSingle; MaximizeBox = false; StartPosition = FormStartPosition.CenterScreen; ClientSize = new Size(372, 648); Font = new Font("맑은 고딕", 9f); int y = 10; const int lx = 14, cx = 130, w = 100; // ---- 반복할 키 ---- GroupBox grp = new GroupBox(); grp.Text = "반복할 키"; grp.Location = new Point(lx, y); grp.Size = new Size(344, 262); rdoSingle = new RadioButton(); rdoSingle.Text = "단일 키"; rdoSingle.Location = new Point(12, 22); rdoSingle.AutoSize = true; rdoSingle.Checked = true; rdoSingle.CheckedChanged += delegate { UpdateModeEnabled(); if (!loading) SaveConfig(); }; grp.Controls.Add(rdoSingle); txtKey = new TextBox(); txtKey.Location = new Point(100, 20); txtKey.Size = new Size(140, 24); txtKey.ReadOnly = true; txtKey.TextAlign = HorizontalAlignment.Center; grp.Controls.Add(txtKey); btnKey = new Button(); btnKey.Text = "키 지정"; btnKey.Location = new Point(248, 19); btnKey.Size = new Size(84, 26); btnKey.Click += delegate { BeginCapture(CAP_SINGLE); }; grp.Controls.Add(btnKey); chkCtrl = NewModCheck("Ctrl", 100, 50, grp); chkShift = NewModCheck("Shift", 160, 50, grp); chkAlt = NewModCheck("Alt", 228, 50, grp); rdoSeq = new RadioButton(); rdoSeq.Text = "키 순서 (최대 " + MAX_STEPS + "단계)"; rdoSeq.Location = new Point(12, 80); rdoSeq.AutoSize = true; grp.Controls.Add(rdoSeq); lstSeq = new ListBox(); lstSeq.Location = new Point(12, 104); lstSeq.Size = new Size(228, 116); lstSeq.IntegralHeight = false; lstSeq.SelectedIndexChanged += delegate { OnSeqSelected(); }; grp.Controls.Add(lstSeq); btnAdd = NewSmallButton("키 추가", 248, 103, 84, grp); btnAdd.Click += delegate { BeginCapture(CAP_STEP); }; btnDel = NewSmallButton("삭제", 248, 133, 84, grp); btnDel.Click += delegate { DeleteStep(); }; btnUp = NewSmallButton("▲", 248, 163, 40, grp); btnUp.Click += delegate { MoveStep(-1); }; btnDown = NewSmallButton("▼", 292, 163, 40, grp); btnDown.Click += delegate { MoveStep(1); }; btnClear = NewSmallButton("비우기", 248, 193, 84, grp); btnClear.Click += delegate { steps.Clear(); RefreshSeqList(-1); SaveConfig(); }; Label lw = new Label(); lw.Text = "각 단계 후 대기 (ms)"; lw.Location = new Point(12, 232); lw.AutoSize = true; grp.Controls.Add(lw); numStepWait = new NumericUpDown(); numStepWait.Location = new Point(140, 229); numStepWait.Size = new Size(100, 24); numStepWait.Minimum = 0; numStepWait.Maximum = 3600000; numStepWait.Value = 100; numStepWait.ValueChanged += delegate { OnStepWaitChanged(); }; grp.Controls.Add(numStepWait); Controls.Add(grp); y += 272; // ---- 입력 방식 ---- AddLabel("입력 방식", lx, y + 4); cboPress = new ComboBox(); cboPress.Location = new Point(cx, y); cboPress.Size = new Size(w + 30, 24); cboPress.DropDownStyle = ComboBoxStyle.DropDownList; cboPress.Items.AddRange(new object[] { "누르기 (탭)", "누르고 있기" }); cboPress.SelectedIndex = 0; cboPress.SelectedIndexChanged += delegate { UpdateModeEnabled(); }; Controls.Add(cboPress); y += 32; AddLabel("누르고 있을 시간 (ms)", lx, y + 4); numHold = new NumericUpDown(); numHold.Location = new Point(cx + 20, y); numHold.Size = new Size(w - 20, 24); numHold.Minimum = 1; numHold.Maximum = 600000; numHold.Value = 500; Controls.Add(numHold); AddHint("탭은 " + TAP_MS + "ms", cx + w + 8, y + 4); y += 32; AddLabel("반복 간격 (ms)", lx, y + 4); numInterval = new NumericUpDown(); numInterval.Location = new Point(cx, y); numInterval.Size = new Size(w, 24); numInterval.Minimum = 1; numInterval.Maximum = 3600000; numInterval.Value = 100; numInterval.ValueChanged += delegate { UpdateCps(); }; Controls.Add(numInterval); lblCps = new Label(); lblCps.Location = new Point(cx + w + 8, y + 4); lblCps.AutoSize = true; lblCps.ForeColor = Color.DimGray; Controls.Add(lblCps); y += 32; AddLabel("랜덤 편차 (%)", lx, y + 4); numJitter = new NumericUpDown(); numJitter.Location = new Point(cx, y); numJitter.Size = new Size(w, 24); numJitter.Minimum = 0; numJitter.Maximum = 90; numJitter.Value = 0; Controls.Add(numJitter); y += 32; AddLabel("반복 횟수", lx, y + 4); numRepeat = new NumericUpDown(); numRepeat.Location = new Point(cx, y); numRepeat.Size = new Size(w, 24); numRepeat.Minimum = 0; numRepeat.Maximum = 100000000; numRepeat.Value = 0; Controls.Add(numRepeat); AddHint("0 = 무한", cx + w + 8, y + 4); y += 32; AddLabel("입력 신호", lx, y + 4); cboMethod = new ComboBox(); cboMethod.Location = new Point(cx, y); cboMethod.Size = new Size(w + 60, 24); cboMethod.DropDownStyle = ComboBoxStyle.DropDownList; cboMethod.Items.AddRange(new object[] { "스캔 코드 (게임 권장)", "가상 키 (호환 모드)" }); cboMethod.SelectedIndex = 0; Controls.Add(cboMethod); y += 36; AddLabel("시작/정지 키", lx, y + 4); txtHotkey = new TextBox(); txtHotkey.Location = new Point(cx, y); txtHotkey.Size = new Size(w, 24); txtHotkey.ReadOnly = true; txtHotkey.TextAlign = HorizontalAlignment.Center; Controls.Add(txtHotkey); btnSetHotkey = new Button(); btnSetHotkey.Text = "변경"; btnSetHotkey.Location = new Point(cx + w + 8, y - 1); btnSetHotkey.Size = new Size(80, 26); btnSetHotkey.Click += delegate { BeginCapture(CAP_HOTKEY); }; Controls.Add(btnSetHotkey); y += 28; AddHint("키 지정·변경을 누른 뒤 원하는 키를 누르세요 (Esc = 취소)", lx, y); y += 20; lblMsg = new Label(); lblMsg.Location = new Point(lx, y); lblMsg.Size = new Size(344, 18); lblMsg.ForeColor = Color.Firebrick; Controls.Add(lblMsg); y += 22; chkTopMost = new CheckBox(); chkTopMost.Text = "항상 위에 표시"; chkTopMost.Location = new Point(lx, y); chkTopMost.AutoSize = true; chkTopMost.CheckedChanged += delegate { TopMost = chkTopMost.Checked; }; Controls.Add(chkTopMost); y += 30; btnToggle = new Button(); btnToggle.Location = new Point(lx, y); btnToggle.Size = new Size(344, 40); btnToggle.Font = new Font("맑은 고딕", 11f, FontStyle.Bold); btnToggle.Click += delegate { Toggle(); }; Controls.Add(btnToggle); y += 48; lblStatus = new Label(); lblStatus.Location = new Point(lx, y); lblStatus.AutoSize = true; lblStatus.Font = new Font("맑은 고딕", 10f, FontStyle.Bold); Controls.Add(lblStatus); lblCount = new Label(); lblCount.Location = new Point(lx + 200, y + 1); lblCount.AutoSize = true; lblCount.ForeColor = Color.DimGray; lblCount.Text = "반복 수: 0"; Controls.Add(lblCount); } private CheckBox NewModCheck(string text, int x, int y, Control parent) { CheckBox c = new CheckBox(); c.Text = text; c.Location = new Point(x, y); c.AutoSize = true; c.CheckedChanged += delegate { if (!loading) { RefreshKeyText(); SaveConfig(); } }; parent.Controls.Add(c); return c; } private static Button NewSmallButton(string text, int x, int y, int width, Control parent) { Button b = new Button(); b.Text = text; b.Location = new Point(x, y); b.Size = new Size(width, 26); parent.Controls.Add(b); return b; } private void AddLabel(string text, int x, int y) { Label l = new Label(); l.Text = text; l.Location = new Point(x, y); l.AutoSize = true; Controls.Add(l); } private void AddHint(string text, int x, int y) { Label l = new Label(); l.Text = text; l.Location = new Point(x, y); l.AutoSize = true; l.ForeColor = Color.DimGray; Controls.Add(l); } // ===================================================================== // 화면 갱신 // ===================================================================== private int SingleMods() { return (chkCtrl.Checked ? Mod.Ctrl : 0) | (chkShift.Checked ? Mod.Shift : 0) | (chkAlt.Checked ? Mod.Alt : 0); } private void RefreshKeyText() { if (capturing == CAP_SINGLE) txtKey.Text = "키를 누르세요..."; else txtKey.Text = singleKey == Keys.None ? "(없음)" : ComboName(singleKey, SingleMods()); } private void RefreshSeqList(int select) { lstSeq.BeginUpdate(); lstSeq.Items.Clear(); for (int i = 0; i < steps.Count; i++) { Step s = steps[i]; lstSeq.Items.Add((i + 1) + ". " + ComboName(s.Key, s.Mods) + " → " + s.WaitMs.ToString("N0") + "ms"); } if (capturing == CAP_STEP) lstSeq.Items.Add("(추가할 키를 누르세요...)"); lstSeq.EndUpdate(); if (select >= 0 && select < steps.Count) lstSeq.SelectedIndex = select; UpdateModeEnabled(); } private void OnSeqSelected() { int i = lstSeq.SelectedIndex; if (i >= 0 && i < steps.Count) { loading = true; numStepWait.Value = Math.Min(numStepWait.Maximum, Math.Max(numStepWait.Minimum, steps[i].WaitMs)); loading = false; } UpdateModeEnabled(); } // 단계를 골라 둔 상태에서 대기 시간을 바꾸면 그 단계에 바로 반영 private void OnStepWaitChanged() { if (loading) return; int i = lstSeq.SelectedIndex; if (i >= 0 && i < steps.Count) { steps[i].WaitMs = (int)numStepWait.Value; RefreshSeqList(i); SaveConfig(); } } private void DeleteStep() { int i = lstSeq.SelectedIndex; if (i < 0 || i >= steps.Count) return; steps.RemoveAt(i); RefreshSeqList(Math.Min(i, steps.Count - 1)); SaveConfig(); } private void MoveStep(int dir) { int i = lstSeq.SelectedIndex; int j = i + dir; if (i < 0 || i >= steps.Count || j < 0 || j >= steps.Count) return; Step t = steps[i]; steps[i] = steps[j]; steps[j] = t; RefreshSeqList(j); SaveConfig(); } private void UpdateModeEnabled() { if (rdoSingle == null || cboPress == null) return; bool idle = !running && capturing == CAP_NONE; bool single = rdoSingle.Checked; int sel = lstSeq.SelectedIndex; bool hasSel = sel >= 0 && sel < steps.Count; rdoSingle.Enabled = !running; rdoSeq.Enabled = !running; txtKey.Enabled = single; btnKey.Enabled = single && idle; chkCtrl.Enabled = chkShift.Enabled = chkAlt.Enabled = single && !running; lstSeq.Enabled = !single; btnAdd.Enabled = !single && idle && steps.Count < MAX_STEPS; btnDel.Enabled = !single && idle && hasSel; btnUp.Enabled = !single && idle && hasSel && sel > 0; btnDown.Enabled = !single && idle && hasSel && sel < steps.Count - 1; btnClear.Enabled = !single && idle && steps.Count > 0; numStepWait.Enabled = !single && !running; numHold.Enabled = cboPress.SelectedIndex == 1; btnSetHotkey.Enabled = idle; } private void UpdateCps() { double ms = (double)numInterval.Value; lblCps.Text = "= 초당 " + (1000.0 / ms).ToString("0.##") + "회"; } private void UpdateHotkeyText() { txtHotkey.Text = capturing == CAP_HOTKEY ? "키 입력..." : KeyName(hotkey); } private void UpdateStatus() { if (running) { lblStatus.Text = "● 실행 중"; lblStatus.ForeColor = Color.Firebrick; btnToggle.Text = "정지 (" + KeyName(hotkey) + ")"; } else { lblStatus.Text = "○ 대기 중"; lblStatus.ForeColor = Color.SeaGreen; btnToggle.Text = "시작 (" + KeyName(hotkey) + ")"; } UpdateModeEnabled(); } private void ShowMsg(string s) { lblMsg.Text = s ?? ""; } private static string ComboName(Keys k, int mods) { StringBuilder sb = new StringBuilder(); if ((mods & Mod.Ctrl) != 0) sb.Append("Ctrl+"); if ((mods & Mod.Shift) != 0) sb.Append("Shift+"); if ((mods & Mod.Alt) != 0) sb.Append("Alt+"); sb.Append(KeyName(k)); return sb.ToString(); } private static string KeyName(Keys k) { if (k >= Keys.D0 && k <= Keys.D9) return ((char)('0' + (k - Keys.D0))).ToString(); if (k >= Keys.NumPad0 && k <= Keys.NumPad9) return "숫자패드 " + (k - Keys.NumPad0); switch (k) { case Keys.Space: return "Space"; case Keys.Return: return "Enter"; case Keys.Back: return "Backspace"; case Keys.Escape: return "Esc"; case Keys.Capital: return "CapsLock"; case Keys.Prior: return "PageUp"; case Keys.Next: return "PageDown"; case Keys.Left: return "←"; case Keys.Right: return "→"; case Keys.Up: return "↑"; case Keys.Down: return "↓"; case Keys.Oemtilde: return "`"; case Keys.OemMinus: return "-"; case Keys.Oemplus: return "="; case Keys.OemOpenBrackets: return "["; case Keys.Oem6: return "]"; case Keys.Oem5: return "\\"; case Keys.Oem1: return ";"; case Keys.Oem7: return "'"; case Keys.Oemcomma: return ","; case Keys.OemPeriod: return "."; case Keys.OemQuestion: return "/"; case Keys.Multiply: return "숫자패드 *"; case Keys.Add: return "숫자패드 +"; case Keys.Subtract: return "숫자패드 -"; case Keys.Divide: return "숫자패드 /"; case Keys.Decimal: return "숫자패드 ."; case Keys.HanguelMode: return "한/영"; case Keys.HanjaMode: return "한자"; default: return k.ToString(); } } // ===================================================================== // 키 지정 (전역 후킹으로 받는다 — 창에 포커스가 없어도 되고, Tab·Enter 같은 키도 받힌다) // ===================================================================== private void BeginCapture(int what) { if (running) return; InstallHook(); ShowMsg(""); capturing = what; if (what == CAP_SINGLE) RefreshKeyText(); else if (what == CAP_STEP) { RefreshSeqList(-1); lstSeq.TopIndex = Math.Max(0, lstSeq.Items.Count - 1); } else UpdateHotkeyText(); UpdateModeEnabled(); } private void EndCapture(Keys k, int mods, bool cancelled) { int what = capturing; capturing = CAP_NONE; if (!cancelled) { if (what == CAP_HOTKEY) { if (IsRepeatedKey(k)) ShowMsg("반복할 키와 같은 키는 시작/정지 키로 쓸 수 없습니다."); else hotkey = k; } else if (k == hotkey) { ShowMsg("시작/정지 키(" + KeyName(hotkey) + ")는 반복할 키로 쓸 수 없습니다."); } else if (what == CAP_SINGLE) { singleKey = k; loading = true; chkCtrl.Checked = (mods & Mod.Ctrl) != 0; chkShift.Checked = (mods & Mod.Shift) != 0; chkAlt.Checked = (mods & Mod.Alt) != 0; loading = false; } else if (what == CAP_STEP && steps.Count < MAX_STEPS) { steps.Add(new Step(k, mods, (int)numStepWait.Value)); } } RefreshKeyText(); RefreshSeqList(what == CAP_STEP && !cancelled ? steps.Count - 1 : lstSeq.SelectedIndex); UpdateHotkeyText(); UpdateStatus(); SaveConfig(); } private bool IsRepeatedKey(Keys k) { if (k == singleKey) return true; foreach (Step s in steps) if (s.Key == k) return true; return false; } private static int CurrentMods() { int m = 0; if ((Native.GetAsyncKeyState((int)Keys.ControlKey) & 0x8000) != 0) m |= Mod.Ctrl; if ((Native.GetAsyncKeyState((int)Keys.ShiftKey) & 0x8000) != 0) m |= Mod.Shift; if ((Native.GetAsyncKeyState((int)Keys.Menu) & 0x8000) != 0) m |= Mod.Alt; return m; } private static bool IsModifier(Keys k) { return k == Keys.ShiftKey || k == Keys.LShiftKey || k == Keys.RShiftKey || k == Keys.ControlKey || k == Keys.LControlKey || k == Keys.RControlKey || k == Keys.Menu || k == Keys.LMenu || k == Keys.RMenu || k == Keys.LWin || k == Keys.RWin; } // 후킹을 (다시) 설치한다. Windows 는 응답이 늦은 저수준 후킹을 알림 없이 제거하므로, // 키를 새로 지정할 때마다 다시 걸어 두면 혹시 떨어진 후킹도 복구된다. private void InstallHook() { UninstallHook(); IntPtr hMod = Native.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName); hookId = Native.SetWindowsHookEx(Native.WH_KEYBOARD_LL, hookProc, hMod, 0); } private void UninstallHook() { if (hookId != IntPtr.Zero) { Native.UnhookWindowsHookEx(hookId); hookId = IntPtr.Zero; } } // ---- 전역 키보드 후킹 ---- private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { int msg = wParam.ToInt32(); bool isDown = msg == Native.WM_KEYDOWN || msg == Native.WM_SYSKEYDOWN; bool isUp = msg == Native.WM_KEYUP || msg == Native.WM_SYSKEYUP; Native.KBDLLHOOKSTRUCT data = (Native.KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.KBDLLHOOKSTRUCT)); Keys vk = (Keys)data.vkCode; // 이 프로그램이 보낸 키는 무시 (자기 자신을 토글하거나 캡처하지 않도록) bool self = data.dwExtraInfo == Native.SELF_TAG; if (!self) { if (isDown && capturing != CAP_NONE) { // 다른 프로그램이 만든 입력도 캡처하지 않는다 — 사람이 누른 키만 if ((data.flags & Native.LLKHF_INJECTED) == 0 && !IsModifier(vk)) { bool cancel = (vk == Keys.Escape); int mods = CurrentMods(); BeginInvoke(new Action(delegate { EndCapture(vk, mods, cancel); })); return (IntPtr)1; // 캡처 중인 키는 다른 프로그램으로 전달하지 않음 } } else if (vk == hotkey) { if (isDown && !hotkeyHeld) { hotkeyHeld = true; BeginInvoke(new Action(Toggle)); } else if (isUp) { hotkeyHeld = false; } } } } return Native.CallNextHookEx(hookId, nCode, wParam, lParam); } // ===================================================================== // 시작 / 정지 // ===================================================================== private void Toggle() { if (running) Stop(); else Start(); } private void Start() { if (running || capturing != CAP_NONE) return; List plan = new List(); if (rdoSingle.Checked) { if (singleKey == Keys.None) { ShowMsg("먼저 [키 지정]으로 반복할 키를 정하세요."); return; } plan.Add(new Step(singleKey, SingleMods(), 0)); } else { if (steps.Count == 0) { ShowMsg("먼저 [키 추가]로 키 순서를 만드세요."); return; } foreach (Step s in steps) plan.Add(new Step(s.Key, s.Mods, s.WaitMs)); } foreach (Step s in plan) { if (s.Key == hotkey) { ShowMsg("시작/정지 키(" + KeyName(hotkey) + ")가 반복할 키에 들어 있습니다."); return; } } ShowMsg(""); int gen = ++generation; int hold = cboPress.SelectedIndex == 1 ? (int)numHold.Value : TAP_MS; int interval = (int)numInterval.Value; int jitter = (int)numJitter.Value; long limit = (long)numRepeat.Value; useScanCodes = cboMethod.SelectedIndex == 0; Interlocked.Exchange(ref cycleCount, 0); running = true; UpdateStatus(); SaveConfig(); worker = new Thread(delegate () { Run(gen, plan, hold, interval, jitter, limit); }); worker.IsBackground = true; worker.Priority = ThreadPriority.AboveNormal; worker.Start(); } // 작업 스레드를 기다리지 않는다(Join 금지). 작업 스레드는 정지되면 눌려 있던 키의 뗌을 // SendInput 으로 보내는데, 그 입력은 UI 스레드의 키보드 후킹을 거쳐야 한다. // UI 스레드가 Join 으로 막혀 있으면 서로 기다리다 후킹이 시간 초과되고, // Windows 는 시간 초과된 저수준 후킹을 알림 없이 제거해 버린다. private void Stop() { running = false; worker = null; UpdateStatus(); } // 이번 실행이 아직 유효한지. 정지 직후 재시작하면 이전 작업 스레드가 잠깐 남아 있을 수 // 있는데, 세대(gen)가 다르면 곧바로 빠져나가게 해서 두 스레드가 겹쳐 입력하지 않게 한다. private bool Alive(int gen) { return running && gen == generation; } private void Run(int gen, List plan, int hold, int interval, int jitter, long limit) { try { long done = 0; while (Alive(gen)) { for (int i = 0; i < plan.Count && Alive(gen); i++) { PressStep(gen, plan[i], hold); if (plan[i].WaitMs > 0 && Alive(gen)) PreciseWait(gen, plan[i].WaitMs); } if (!Alive(gen)) break; done++; Interlocked.Increment(ref cycleCount); if (limit > 0 && done >= limit) break; double wait = interval; if (jitter > 0) { double delta = interval * (jitter / 100.0); lock (rnd) wait = interval + (rnd.NextDouble() * 2 - 1) * delta; if (wait < 1) wait = 1; } PreciseWait(gen, wait); } } finally { ReleaseAll(); // 어떤 경우에도 눌린 채로 남기지 않는다 } // 반복 횟수를 채워 스스로 끝난 경우에만 상태를 되돌린다 (재시작된 새 실행은 건드리지 않음) if (gen == generation) { running = false; try { BeginInvoke(new Action(UpdateStatus)); } catch { /* 폼이 이미 닫힌 경우 */ } } } // 조합키 누름 → 키 누름 → hold ms 유지 → 키 뗌 → 조합키 뗌. // 게임은 매 프레임 키 상태를 읽으므로 누르고 떼는 사이에 실제로 시간을 둔다. // 정지되면 대기를 끊고 곧바로 떼므로 키가 눌린 채로 남지 않는다. private void PressStep(int gen, Step s, int hold) { List mods = new List(); if ((s.Mods & Mod.Ctrl) != 0) mods.Add(Keys.LControlKey); if ((s.Mods & Mod.Shift) != 0) mods.Add(Keys.LShiftKey); if ((s.Mods & Mod.Alt) != 0) mods.Add(Keys.LMenu); foreach (Keys m in mods) SendKey(m, false); if (mods.Count > 0) PreciseWait(gen, 10); // 조합키가 먼저 인식될 틈 if (Alive(gen)) { SendKey(s.Key, false); PreciseWait(gen, hold); SendKey(s.Key, true); } for (int i = mods.Count - 1; i >= 0; i--) SendKey(mods[i], true); } private void SendKey(Keys key, bool up) { int vk = (int)key; bool ext; ushort scan = ScanCodeOf(key, out ext); Native.INPUT[] inputs = new Native.INPUT[1]; inputs[0].type = Native.INPUT_KEYBOARD; uint flags = up ? Native.KEYEVENTF_KEYUP : 0; if (ext) flags |= Native.KEYEVENTF_EXTENDEDKEY; if (useScanCodes && scan != 0) { // 스캔 코드 방식: DirectInput·Raw Input 으로 키보드를 읽는 게임도 실제 키처럼 받는다 inputs[0].u.ki.wVk = 0; inputs[0].u.ki.wScan = scan; flags |= Native.KEYEVENTF_SCANCODE; } else { // 가상 키 방식(호환 모드) — 스캔 코드가 없는 키도 이쪽으로 보낸다 inputs[0].u.ki.wVk = (ushort)vk; inputs[0].u.ki.wScan = scan; } inputs[0].u.ki.dwFlags = flags; inputs[0].u.ki.dwExtraInfo = Native.SELF_TAG; lock (downKeys) { if (up) downKeys.Remove(vk); else downKeys[vk] = true; } Native.SendInput(1, inputs, Marshal.SizeOf(typeof(Native.INPUT))); } private void ReleaseAll() { List keys; lock (downKeys) keys = new List(downKeys.Keys); foreach (int vk in keys) SendKey((Keys)vk, true); } // 확장 키(E0 접두)는 따로 표시해야 방향키가 숫자패드로 들어가지 않는다 private static ushort ScanCodeOf(Keys k, out bool extended) { switch (k) { case Keys.Insert: case Keys.Delete: case Keys.Home: case Keys.End: case Keys.PageUp: case Keys.PageDown: case Keys.Left: case Keys.Right: case Keys.Up: case Keys.Down: case Keys.RControlKey: case Keys.RMenu: case Keys.LWin: case Keys.RWin: case Keys.Apps: case Keys.Divide: case Keys.NumLock: case Keys.PrintScreen: extended = true; break; default: extended = false; break; } return (ushort)(Native.MapVirtualKey((uint)k, Native.MAPVK_VK_TO_VSC) & 0xFF); } // Thread.Sleep 오차를 줄인 대기 (짧은 간격에서도 정확도 유지) private void PreciseWait(int gen, double ms) { Stopwatch sw = Stopwatch.StartNew(); while (true) { double remain = ms - sw.Elapsed.TotalMilliseconds; if (remain <= 0) return; if (!Alive(gen)) return; if (remain > 20) Thread.Sleep(10); else if (remain > 2) Thread.Sleep(1); else Thread.SpinWait(50); } } // ===================================================================== // 설정 저장 / 불러오기 (autokey.ini — exe 와 같은 폴더) // ===================================================================== private void SaveConfig() { if (loading) return; try { StringBuilder sb = new StringBuilder(); sb.AppendLine("mode=" + (rdoSeq.Checked ? 1 : 0)); sb.AppendLine("key=" + (int)singleKey); sb.AppendLine("mods=" + SingleMods()); StringBuilder seq = new StringBuilder(); foreach (Step s in steps) { if (seq.Length > 0) seq.Append(';'); seq.Append((int)s.Key).Append(':').Append(s.Mods).Append(':').Append(s.WaitMs); } sb.AppendLine("seq=" + seq); sb.AppendLine("stepwait=" + (int)numStepWait.Value); sb.AppendLine("press=" + cboPress.SelectedIndex); sb.AppendLine("hold=" + (int)numHold.Value); sb.AppendLine("interval=" + (int)numInterval.Value); sb.AppendLine("jitter=" + (int)numJitter.Value); sb.AppendLine("repeat=" + (long)numRepeat.Value); sb.AppendLine("method=" + cboMethod.SelectedIndex); sb.AppendLine("hotkey=" + (int)hotkey); sb.AppendLine("topmost=" + (chkTopMost.Checked ? 1 : 0)); File.WriteAllText(configPath, sb.ToString(), Encoding.UTF8); } catch { /* 저장 실패는 무시 */ } } private void LoadConfig() { try { if (!File.Exists(configPath)) return; foreach (string line in File.ReadAllLines(configPath)) { int i = line.IndexOf('='); if (i <= 0) continue; string key = line.Substring(0, i).Trim(); string val = line.Substring(i + 1).Trim(); if (key == "seq") { LoadSeq(val); continue; } long n; if (!long.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out n)) continue; switch (key) { case "mode": rdoSeq.Checked = n == 1; rdoSingle.Checked = n != 1; break; case "key": if (n > 0 && n < 256 && !IsModifier((Keys)n)) singleKey = (Keys)n; break; case "mods": chkCtrl.Checked = (n & Mod.Ctrl) != 0; chkShift.Checked = (n & Mod.Shift) != 0; chkAlt.Checked = (n & Mod.Alt) != 0; break; case "stepwait": numStepWait.Value = Clamp(n, numStepWait); break; case "press": if (n >= 0 && n < cboPress.Items.Count) cboPress.SelectedIndex = (int)n; break; case "hold": numHold.Value = Clamp(n, numHold); break; case "interval": numInterval.Value = Clamp(n, numInterval); break; case "jitter": numJitter.Value = Clamp(n, numJitter); break; case "repeat": numRepeat.Value = Clamp(n, numRepeat); break; case "method": if (n >= 0 && n < cboMethod.Items.Count) cboMethod.SelectedIndex = (int)n; break; case "hotkey": if (n > 0 && n < 256 && !IsModifier((Keys)n)) hotkey = (Keys)n; break; case "topmost": chkTopMost.Checked = n == 1; break; } } } catch { /* 손상된 설정 파일은 무시 */ } } private void LoadSeq(string val) { steps.Clear(); foreach (string part in val.Split(';')) { if (steps.Count >= MAX_STEPS) break; string[] f = part.Split(':'); if (f.Length != 3) continue; int vk, mods, wait; if (!int.TryParse(f[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out vk)) continue; if (!int.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out mods)) continue; if (!int.TryParse(f[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out wait)) continue; if (vk <= 0 || vk >= 256 || IsModifier((Keys)vk)) continue; steps.Add(new Step((Keys)vk, mods & 7, Math.Max(0, Math.Min(3600000, wait)))); } } private static decimal Clamp(long v, NumericUpDown nud) { decimal d = v; if (d < nud.Minimum) return nud.Minimum; if (d > nud.Maximum) return nud.Maximum; return d; } protected override void OnFormClosing(FormClosingEventArgs e) { running = false; SaveConfig(); UninstallHook(); ReleaseAll(); // 작업 스레드가 떼기 전에 프로세스가 끝나도 키가 눌린 채로 남지 않게 base.OnFormClosing(e); } } internal static class Program { [STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }