public void KeyPress(WinAPI.VK key) { if (_doKeyPress != null) { _doKeyPress(key); } }
internal KeySetting CreateNew(WinAPI.VK inputKey) { ConfigurationElement element = CreateNewElement(); KeySetting settings = element as KeySetting; settings.InputKey = inputKey; settings.OutputKey = inputKey; base.BaseAdd(element); return settings; }
public static KeyboardInput CreateFrom(WinAPI.WM wParam, Mubox.WinAPI.WindowHook.KBDLLHOOKSTRUCT hookStruct) { KeyboardInput e = new KeyboardInput(); e.VK = hookStruct.vkCode; e.Scan = hookStruct.scanCode; e.Flags = hookStruct.flags; e.Time = hookStruct.time; e.WM = wParam; return e; }
public static void Convert(ref WinAPI.POINT point, int resX, int resY) { //point.x = (int)(((float)point.x + (float)NoteOffsetX) * ((float)resX / (float)DefaultResX)); //point.y = (int)(((float)point.y + (float)NoteOffsetY) * ((float)resY / (float)DefaultResY)); point.x = (int)(1.6f * point.x) + 106; point.y = (int)(1.4f * point.y) + 106; point.x = (int)((float)point.x * (float)resX / 1024f); point.y = (int)((float)point.y * (float)resY / 768f); }
public KeySetting GetOrCreateNew(WinAPI.VK inputKey) { foreach (KeySetting s in this) { if (s.InputKey.Equals(inputKey)) { return s; } } return CreateNew(inputKey); }
public static void Write <T>(this Process targetProcess, IntPtr address, T value, params int[] offsets) where T : struct { if (targetProcess == null) { return; } int last = OffsetAddress(targetProcess, ref address, offsets); if (address == IntPtr.Zero) { return; } byte[] buffer = null; if (typeof(T) == typeof(bool)) { buffer = BitConverter.GetBytes(Convert.ToBoolean(value)); } else if (typeof(T) == typeof(byte)) { buffer = BitConverter.GetBytes(Convert.ToByte(value)); } else if (typeof(T) == typeof(sbyte)) { buffer = BitConverter.GetBytes(Convert.ToSByte(value)); } else if (typeof(T) == typeof(int)) { buffer = BitConverter.GetBytes(Convert.ToInt32(value)); } else if (typeof(T) == typeof(uint)) { buffer = BitConverter.GetBytes(Convert.ToUInt32(value)); } else if (typeof(T) == typeof(short)) { buffer = BitConverter.GetBytes(Convert.ToInt16(value)); } else if (typeof(T) == typeof(ushort)) { buffer = BitConverter.GetBytes(Convert.ToUInt16(value)); } else if (typeof(T) == typeof(long)) { buffer = BitConverter.GetBytes(Convert.ToInt64(value)); } else if (typeof(T) == typeof(ulong)) { buffer = BitConverter.GetBytes(Convert.ToUInt64(value)); } else if (typeof(T) == typeof(float)) { buffer = BitConverter.GetBytes(Convert.ToSingle(value)); } else if (typeof(T) == typeof(double)) { buffer = BitConverter.GetBytes(Convert.ToDouble(value)); } int bytesWritten; WinAPI.WriteProcessMemory(targetProcess.Handle, address + last, buffer, buffer.Length, out bytesWritten); }
public static bool GetKeyDownAsync(WinAPI.VirtualKeyShort key) { return Convert.ToBoolean(WinAPI.GetAsyncKeyState(key) & WinAPI.KEY_PRESSED); }
/// <summary> /// Returns whether the given key was down at time of the last Update-call /// </summary> /// <param name="key">Key to check</param> /// <returns></returns> public bool KeyIsDown(WinAPI.VirtualKeyShort key) { return KeyIsDown((int) key); }
public static IntPtr Callback(int nCode, IntPtr wParam, IntPtr lParam) { if (MMain.mahou == null || nCode < 0) { return(WinAPI.CallNextHookEx(_LLHook_ID, nCode, wParam, lParam)); } if (KMHook.ExcludedProgram() && !MahouUI.ChangeLayoutInExcluded) { return(WinAPI.CallNextHookEx(_LLHook_ID, nCode, wParam, lParam)); } var vk = Marshal.ReadInt32(lParam); var Key = (Keys)vk; if (MahouUI.BlockAltUpNOW) { if ((wParam == (IntPtr)WinAPI.WM_SYSKEYUP || wParam == (IntPtr)WinAPI.WM_KEYUP) && (Key == Keys.LMenu || Key == Keys.RMenu || Key == Keys.Menu)) { Debug.WriteLine("ihihihihihihihih-hihih-hi blocked alt :)))))"); MahouUI.BlockAltUpNOW = false; return((IntPtr)1); } } SetModifs(Key, wParam); if (MahouUI.SnippetsEnabled) { if (KMHook.c_snip.Count > 0) { if (MMain.mahou.SnippetsExpandType == "Tab" && Key == Keys.Tab && !shift && !alt && !win && !ctrl) { WinAPI.keybd_event((byte)Keys.F14, (byte)Keys.F14, (int)WinAPI.KEYEVENTF_KEYUP, 0); return((IntPtr)1); // Disable event } } } if (MahouUI.RemapCapslockAsF18) { bool _shift = !shift, _alt = !alt, _ctrl = !ctrl, _win = !win; if (Key == Keys.CapsLock) { for (int i = 1; i != 5; i++) { var KeyIndex = (int)typeof(MahouUI).GetField("Key" + i).GetValue(MMain.mahou); if (KeyIndex == 8) // Shift+CapsLock { _shift = shift; } } } uint mods = 0; if (alt) { mods += WinAPI.MOD_ALT; } if (ctrl) { mods += WinAPI.MOD_CONTROL; } if (shift) { mods += WinAPI.MOD_SHIFT; } if (win) { mods += WinAPI.MOD_WIN; } bool has = MMain.mahou.HasHotkey(new Hotkey(false, (uint)Keys.F18, mods, 77)); if (has) { if (Hotkey.ContainsModifier((int)mods, (int)WinAPI.MOD_SHIFT)) { _shift = shift; } if (Hotkey.ContainsModifier((int)mods, (int)WinAPI.MOD_ALT)) { _alt = alt; } if (Hotkey.ContainsModifier((int)mods, (int)WinAPI.MOD_CONTROL)) { _ctrl = ctrl; } if (Hotkey.ContainsModifier((int)mods, (int)WinAPI.MOD_WIN)) { _win = win; } } var GJIME = false; if (vk >= 240 && vk <= 242) // GJ IME's Shift/Alt/Ctrl + CapsLock { GJIME = true; } // Debug.WriteLine(Key + " " +has + "// " + _shift + " " + _alt + " " + _ctrl + " " + _win + " " + mods + " >> " + (Key == Keys.CapsLock && _shift && _alt && _ctrl && _win)); if ((Key == Keys.CapsLock || GJIME) && _shift && _alt && _ctrl && _win) { var flags = (int)(KInputs.IsExtended(Key) ? WinAPI.KEYEVENTF_EXTENDEDKEY : 0); if (wParam == (IntPtr)WinAPI.WM_KEYUP) { flags |= (int)WinAPI.KEYEVENTF_KEYUP; } WinAPI.keybd_event((byte)Keys.F18, (byte)Keys.F18, flags, 0); return((IntPtr)1); // Disable event } // Debug.WriteLine(Marshal.GetLastWin32Error()); } return(WinAPI.CallNextHookEx(_LLHook_ID, nCode, wParam, lParam)); }
private static bool OnKeyboardInputReceived(WinAPI.WM wParam, WinAPI.WindowHook.KBDLLHOOKSTRUCT hookStruct) { // ignore injected input if (hookStruct.flags.HasFlag(WinAPI.WindowHook.LLKHF.INJECTED)) { return false; } // coerce specialized left/right shift-state to generalized shift-state if (MuboxConfigSection.Default.Profiles.ActiveProfile.EnableCASFix) { switch ((WinAPI.VK)hookStruct.vkCode) { case WinAPI.VK.LeftShift: case WinAPI.VK.RightShift: hookStruct.vkCode = WinAPI.VK.Shift; break; case WinAPI.VK.LeftMenu: case WinAPI.VK.RightMenu: hookStruct.vkCode = WinAPI.VK.Menu; break; case WinAPI.VK.LeftControl: case WinAPI.VK.RightControl: hookStruct.vkCode = WinAPI.VK.Control; break; } } // ignore "global desktop keys" Mubox.Configuration.KeySetting globalKeySetting = null; if (Mubox.Configuration.MuboxConfigSection.Default.Profiles.ActiveProfile.Keys.TryGetKeySetting((WinAPI.VK)hookStruct.vkCode, out globalKeySetting) && (globalKeySetting.SendToDesktop)) { return false; } // update pressed keys if (!UpdatePressedKeys(hookStruct) && Mubox.Configuration.MuboxConfigSection.Default.IsCaptureEnabled && !Mubox.Configuration.MuboxConfigSection.Default.DisableRepeatKeyFiltering) { return true; } // count if (Performance.IsPerformanceEnabled) { KeyboardInputPerformance.Count(Convert.ToInt64(hookStruct.time)); } // handle high-level if (KeyboardInputReceived != null) { KeyboardInput keyboardInputEventArgs = KeyboardInput.CreateFrom(wParam, hookStruct); { Mubox.Configuration.KeySetting keySetting = globalKeySetting; if (Mubox.Configuration.MuboxConfigSection.Default.Profiles.ActiveProfile != null) { Mubox.Configuration.ClientSettings activeClient = Mubox.Configuration.MuboxConfigSection.Default.Profiles.ActiveProfile.ActiveClient; if (activeClient != null) { activeClient.Keys.TryGetKeySetting((WinAPI.VK)keyboardInputEventArgs.VK, out keySetting); } if (keySetting != null) { keyboardInputEventArgs.VK = keySetting.OutputKey; keyboardInputEventArgs.CAS = keySetting.OutputModifiers; } } } OnKeyboardInputReceivedInternal(keyboardInputEventArgs); return keyboardInputEventArgs.Handled; } return false; }
public virtual void Dispatch(WinAPI.VK vk) { // TODO: scan code mapping should always be done on the destination machine, since it contains hardware/driver specific values var scan = WinAPI.SendInputApi.MapVirtualKeyEx(vk, WinAPI.SendInputApi.MAPVK.MAPVK_VK_TO_VSC, System.Windows.Forms.InputLanguage.CurrentInputLanguage.Handle); Dispatch(new KeyboardInput { WM = Mubox.WinAPI.WM.KEYDOWN, VK = vk, Time = WinAPI.SendInputApi.GetTickCount(), Scan = scan }); System.Threading.Thread.Sleep(0x4d); Dispatch(new KeyboardInput { WM = Mubox.WinAPI.WM.KEYUP, VK = vk, Time = WinAPI.SendInputApi.GetTickCount(), Scan = scan, Flags = WinAPI.WindowHook.LLKHF.UP }); }
private void UnloadLibrary() { WinAPI.UnloadLibrary(HModule); WinAPI.UnloadLibrary(HModule); HModule = Zero; }
public static void KeyUp(VK virtualKeyCode) { INPUT[] input = new INPUT[1]; InputDataFactory(ref input[0], virtualKeyCode, Up: true); WinAPI.SendInput(1, input, Marshal.SizeOf(typeof(INPUT))); }
public static bool IsKeyDown(VK keyCode) { var result = WinAPI.GetAsyncKeyState((UInt16)keyCode); return(result < 0); }
protected override void WndProc(ref Message m) { //Debug.WriteLine(m); switch (m.Msg) { case 0x0201: // WM_LBUTTONDOWN case 0x0202: // WM_LBUTTONUP case 0x0207: // WM_MBUTTONDOWN case 0x0208: // WM_MBUTTONUP case 0x020b: // WM_XBUTTONDOWN case 0x020c: // WM_XBUTTONUP case 0x020A: // WM_MOUSEWHEEL case 0x0100: // WM_KEYDOWN case 0x0101: // WM_KEYUP case 0x0104: // WM_SYSKEYDOWN case 0x0105: // WM_SYSKEYUP case 0x319: // WM_APPCOMMAND if (mp.WindowHandle != IntPtr.Zero) { WinAPI.SendMessage(mp.WindowHandle, m.Msg, m.WParam, m.LParam); } break; case 0x0200: // WM_MOUSEMOVE { if ((DateTime.Now - LastCycleFullscreen).TotalMilliseconds > 500) { Point pos = PointToClient(Cursor.Position); mp.command($"mouse {pos.X} {pos.Y}"); } if (CursorHelp.IsPosDifferent(LastCursorPosChanged)) { CursorHelp.Show(); } } break; case 0x2a3: // WM_MOUSELEAVE // osc won't always auto hide mp.command("mouse 1 1"); break; case 0x203: // WM_LBUTTONDBLCLK { Point pos = PointToClient(Cursor.Position); mp.command($"mouse {pos.X} {pos.Y} 0 double"); } break; case 0x02E0: // WM_DPICHANGED { if (!WasShown) { break; } WinAPI.RECT rect = Marshal.PtrToStructure <WinAPI.RECT>(m.LParam); WinAPI.SetWindowPos(Handle, IntPtr.Zero, rect.Left, rect.Top, rect.Width, rect.Height, 0); } break; case 0x0214: // WM_SIZING { var rc = Marshal.PtrToStructure <WinAPI.RECT>(m.LParam); var r = rc; NativeHelp.SubtractWindowBorders(Handle, ref r); int c_w = r.Right - r.Left, c_h = r.Bottom - r.Top; Size s = mp.VideoSize; if (s == Size.Empty) { s = new Size(16, 9); } float aspect = s.Width / (float)s.Height; int d_w = Convert.ToInt32(c_h * aspect - c_w); int d_h = Convert.ToInt32(c_w / aspect - c_h); int[] d_corners = { d_w, d_h, -d_w, -d_h }; int[] corners = { rc.Left, rc.Top, rc.Right, rc.Bottom }; int corner = NativeHelp.GetResizeBorder(m.WParam.ToInt32()); if (corner >= 0) { corners[corner] -= d_corners[corner]; } Marshal.StructureToPtr <WinAPI.RECT>(new WinAPI.RECT(corners[0], corners[1], corners[2], corners[3]), m.LParam, false); m.Result = new IntPtr(1); } return; case 0x004A: // WM_COPYDATA { var copyData = (WinAPI.COPYDATASTRUCT)m.GetLParam(typeof(WinAPI.COPYDATASTRUCT)); string[] files = copyData.lpData.Split('\n'); string mode = files[0]; files = files.Skip(1).ToArray(); switch (mode) { case "single": mp.Load(files, true, Control.ModifierKeys.HasFlag(Keys.Control)); break; case "queue": foreach (string file in files) { mp.commandv("loadfile", file, "append"); } break; } Activate(); } return; } if (m.Msg == TaskbarButtonCreatedMessage && mp.TaskbarProgress) { Taskbar = new Taskbar(Handle); ProgressTimer.Start(); } base.WndProc(ref m); }
public MainForm() { InitializeComponent(); try { object recent = RegistryHelp.GetValue(App.RegPath, "Recent"); if (recent is string[] r) { RecentFiles = new List <string>(r); } else { RecentFiles = new List <string>(); } Instance = this; Hwnd = Handle; mp.Init(); mp.Shutdown += Shutdown; mp.VideoSizeChanged += VideoSizeChanged; mp.FileLoaded += FileLoaded; mp.Idle += Idle; mp.Seek += () => UpdateProgressBar(); mp.observe_property_bool("pause", PropChangePause); mp.observe_property_bool("fullscreen", PropChangeFullscreen); mp.observe_property_bool("ontop", PropChangeOnTop); mp.observe_property_bool("border", PropChangeBorder); mp.observe_property_string("sid", PropChangeSid); mp.observe_property_string("aid", PropChangeAid); mp.observe_property_string("vid", PropChangeVid); mp.observe_property_int("edition", PropChangeEdition); mp.observe_property_double("window-scale", PropChangeWindowScale); if (mp.GPUAPI != "vulkan") { mp.ProcessCommandLine(false); } AppDomain.CurrentDomain.UnhandledException += (sender, e) => Msg.ShowError(e.ExceptionObject.ToString()); Application.ThreadException += (sender, e) => Msg.ShowException(e.Exception); Msg.SupportURL = "https://github.com/stax76/mpv.net#support"; Text = "mpv.net " + Application.ProductVersion; TaskbarButtonCreatedMessage = WinAPI.RegisterWindowMessage("TaskbarButtonCreated"); ContextMenu = new ContextMenuStripEx(components); ContextMenu.Opened += ContextMenu_Opened; ContextMenu.Opening += ContextMenu_Opening; if (mp.Screen == -1) { mp.Screen = Array.IndexOf(Screen.AllScreens, Screen.PrimaryScreen); } int targetIndex = mp.Screen; Screen[] screens = Screen.AllScreens; if (targetIndex < 0) { targetIndex = 0; } if (targetIndex > screens.Length - 1) { targetIndex = screens.Length - 1; } Screen screen = screens[Array.IndexOf(screens, screens[targetIndex])]; Rectangle target = screen.Bounds; Left = target.X + (target.Width - Width) / 2; Top = target.Y + (target.Height - Height) / 2; int posX = RegistryHelp.GetInt(App.RegPath, "PosX"); int posY = RegistryHelp.GetInt(App.RegPath, "PosY"); if (posX != 0 && posY != 0 && App.RememberPosition) { Left = posX - Width / 2; Top = posY - Height / 2; } if (App.Maximized) { SetFormPosAndSize(1, true); WindowState = FormWindowState.Maximized; } } catch (Exception ex) { Msg.ShowException(ex); } }
void SetFormPosAndSize(double scale = 1, bool force = false) { if (!force) { if (WindowState == FormWindowState.Maximized) { return; } if (mp.Fullscreen) { CycleFullscreen(true); return; } } Screen screen = Screen.FromControl(this); int autoFitHeight = Convert.ToInt32(screen.WorkingArea.Height * mp.Autofit); if (mp.VideoSize.Height == 0 || mp.VideoSize.Width == 0 || mp.VideoSize.Width / (float)mp.VideoSize.Height < App.MinimumAspectRatio) { mp.VideoSize = new Size((int)(autoFitHeight * (16 / 9.0)), autoFitHeight); } Size size = mp.VideoSize; int height = size.Height; if (App.RememberHeight || scale != 1) { if (WasInitialSizeSet || scale != 1) { height = ClientSize.Height; } else { height = autoFitHeight; WasInitialSizeSet = true; } } height = Convert.ToInt32(height * scale); int width = Convert.ToInt32(height * size.Width / (double)size.Height); if (height > screen.WorkingArea.Height * 0.9) { height = Convert.ToInt32(screen.WorkingArea.Height * 0.9); width = Convert.ToInt32(height * size.Width / (double)size.Height); } if (width > screen.WorkingArea.Width * 0.9) { width = Convert.ToInt32(screen.WorkingArea.Width * 0.9); height = Convert.ToInt32(width * size.Height / (double)size.Width); } if (height < screen.WorkingArea.Height * mp.AutofitSmaller) { height = Convert.ToInt32(screen.WorkingArea.Height * mp.AutofitSmaller); width = Convert.ToInt32(height * size.Width / (double)size.Height); } if (height > screen.WorkingArea.Height * mp.AutofitLarger) { height = Convert.ToInt32(screen.WorkingArea.Height * mp.AutofitLarger); width = Convert.ToInt32(height * size.Width / (double)size.Height); } Point middlePos = new Point(Left + Width / 2, Top + Height / 2); var rect = new WinAPI.RECT(new Rectangle(screen.Bounds.X, screen.Bounds.Y, width, height)); NativeHelp.AddWindowBorders(Handle, ref rect); int left = middlePos.X - rect.Width / 2; int top = middlePos.Y - rect.Height / 2; Screen[] screens = Screen.AllScreens; int minLeft = screens.Select(val => val.WorkingArea.X).Min(); int maxRight = screens.Select(val => val.WorkingArea.Right).Max(); int minTop = screens.Select(val => val.WorkingArea.Y).Min(); int maxBottom = screens.Select(val => val.WorkingArea.Bottom).Max(); if (left < minLeft) { left = minLeft; } if (left + rect.Width > maxRight) { left = maxRight - rect.Width; } if (top < minTop) { top = minTop; } if (top + rect.Height > maxBottom) { top = maxBottom - rect.Height; } WinAPI.SetWindowPos(Handle, IntPtr.Zero /* HWND_TOP */, left, top, rect.Width, rect.Height, 4 /* SWP_NOZORDER */); }
/// <summary> /// <para>Updates key state and returns value indicating transitions.</para> /// </summary> /// <param name="vk"></param> /// <param name="scan"></param> /// <param name="flags"></param> /// <param name="time"></param> /// <returns>True if the key state has transitioned.</returns> private bool UpdatePressedKeys(WinAPI.VK vk, uint scan, WinAPI.WindowHook.LLKHF flags, uint time) { var result = false; if (WinAPI.WindowHook.LLKHF.UP != (flags & WinAPI.WindowHook.LLKHF.UP)) { if (!IsKeyPressed(vk)) { result = true; pressedKeys[(int)vk] = 0x80; } } else { if (IsKeyPressed(vk)) { result = true; pressedKeys[(int)vk] = 0x00; } } return result; }
public void KeyPress(WinAPI.VK key) { _muboxClientBridge.KeyPress(key); }
/// <summary> /// Gets caret position from focused window or from focused control in window. /// </summary> /// <returns>Point</returns> public static Point GetCaretPointToScreen(out Point caretOnlyPos) { var LuckyNone = new Point(77777, 77777); caretOnlyPos = LuckyNone; var _cThr_id = WinAPI.GetCurrentThreadId(); var _pntCR = new Point(0, 0); var _fwFCS_Re = new WinAPI.RECT(0, 0, 0, 0); var _fw = WinAPI.GetForegroundWindow(); uint dummy = 0; var _fwThr_id = WinAPI.GetWindowThreadProcessId(_fw, out dummy); IntPtr _fwFCS = IntPtr.Zero; var _clsNMb = new StringBuilder(256); string _clsNMfw = ""; Logging.Log("_c HWND: [" + MMain.MAHOU_HANDLE + "], _c ThrId: [" + _cThr_id + "], " + "_fw HWND: [" + _fw + "]" + ", _fw ThrId: " + _fwThr_id + "."); if (_fwThr_id != _cThr_id) { var gti = new WinAPI.GUITHREADINFO(); gti.cbSize = Marshal.SizeOf(gti); if (!GetGuiInfo(_fwThr_id, ref gti)) { return(LuckyNone); } _fwFCS = gti.hwndFocus; WinAPI.GetClassName(_fw, _clsNMb, _clsNMb.Capacity); _clsNMfw = _clsNMb.ToString(); if (_fwFCS != IntPtr.Zero && _fwFCS != _fw) { var _fwFCSThr_id = WinAPI.GetWindowThreadProcessId(_fwFCS, out dummy); var gtiFCS = new WinAPI.GUITHREADINFO(); gtiFCS.cbSize = Marshal.SizeOf(gtiFCS); if (!GetGuiInfo(_fwFCSThr_id, ref gtiFCS)) { return(LuckyNone); } Logging.Log("_fcs: [" + _fwFCS + "]." + "_fw classname = [" + _clsNMb + "], " + "_fcs thread_id = [" + _fwFCSThr_id + "]."); WinAPI.GetClassName(_fwFCS, _clsNMb, _clsNMb.Capacity); Logging.Log("_fcs classname = [" + _clsNMb + "]."); WinAPI.GetWindowRect(_fwFCS, out _fwFCS_Re); _pntCR = new Point(gtiFCS.rectCaret.Left, gtiFCS.rectCaret.Top); } else { _pntCR = new Point(gti.rectCaret.Left, gti.rectCaret.Top); WinAPI.GetWindowRect(_fw, out _fwFCS_Re); } if (_clsNMfw == "PX_WINDOW_CLASS" && MahouUI.MCDSSupport) { System.Threading.Tasks.Task.Factory.StartNew(GetDataFromMCDS); var CaretToScreen = new Point(_fwFCS_Re.Left, _fwFCS_Re.Top); CaretToScreen.X += _CaretST3.X + SidebarWidth + MahouUI.MCDS_Xpos_temp; if (viewID == 4) { WinAPI.RECT clts = new WinAPI.RECT(0, 0, 0, 0); WinAPI.GetWindowRect(WinAPI.GetForegroundWindow(), out clts); CaretToScreen.Y = clts.Bottom - MahouUI.MCDS_BottomIndent_temp - 45 + MahouUI.MCDS_Ypos_temp; CaretToScreen.X -= 20; } else { CaretToScreen.Y += _CaretST3.Y + MahouUI.MCDS_TopIndent_temp + MahouUI.MCDS_Ypos_temp; } caretOnlyPos = _CaretST3; return(CaretToScreen); } else { if (_pntCR.Equals(new Point(0, 0))) { return(LuckyNone); } Logging.Log("CaretPos = x[" + _pntCR.X + "], y[" + _pntCR.Y + "]."); var _clsNM = _clsNMb.ToString().ToLower(); // Do not display caret for these classes: if (_clsNM.Contains("listbox") || _clsNM.Contains("button") || _clsNM.Contains("checkbox") || _clsNM.Contains("combobox") || _clsNM.Contains("listview") || _clsNM.Contains("pagecontrol") || (_clsNM.Contains("window") && !_clsNM.Contains("mozilla")) || _clsNM.Contains("syslink") || _clsNM.Contains("tree") || _clsNM.Contains("helpform") || _clsNM.Contains("tmainform") || _clsNM.Contains("btn") || _clsNM.Contains("удалить") || _clsNM.Contains("delete") || _clsNM.Contains("afx:") || _clsNM == "msctls_trackbar32" || _clsNM.Contains("wxwindow") || _clsNM == "systabcontrol32" || _clsNM == "directuihwnd" || _clsNM == "static" || _clsNM == "netuihwnd" || _clsNMfw == "mspaintapp" || _clsNM == "potplayer" || _clsNM == "mdiclient" || (_clsNMfw == "#32770" && _clsNM != "edit")) { return(LuckyNone); } if (_clsNM.Contains("sharpdevelop.exe")) { _pntCR.Y += 28; _pntCR.X += 3; } Logging.Log("Get caret position finished successfully.", 0); caretOnlyPos = _pntCR; return(new Point(_fwFCS_Re.Left + _pntCR.X, _fwFCS_Re.Top + _pntCR.Y)); } } return(LuckyNone); }
private static bool OnMouseInputReceived(WinAPI.WM wm, WinAPI.WindowHook.MSLLHOOKSTRUCT hookStruct) { // ignore injected input if (hookStruct.flags.HasFlag(WinAPI.WindowHook.LLMHF.INJECTED)) { return false; } MouseInput mouseInputEventArgs = MouseInput.CreateFrom(wm, hookStruct); if (Performance.IsPerformanceEnabled) { MouseInputPerformance.Count(Convert.ToInt64(mouseInputEventArgs.Time)); } try { if (MouseInputReceived != null) { MouseInputReceived(null, mouseInputEventArgs); return mouseInputEventArgs.Handled; } } catch (Exception ex) { ex.Log(); } return false; }
static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (App.IsStartedFromTerminal) { WinAPI.AttachConsole(-1 /*ATTACH_PARENT_PROCESS*/); } if (mp.ConfigFolder == "") { return; } string[] args = Environment.GetCommandLineArgs().Skip(1).ToArray(); if (args.Length == 2 && args[0] == "--reg-file-assoc") { if (args[1] == "audio") { FileAssociation.Register(App.AudioTypes); } if (args[1] == "video") { FileAssociation.Register(App.VideoTypes); } if (args[1] == "image") { FileAssociation.Register(App.ImageTypes); } if (args[1] == "unreg") { FileAssociation.Unregister(); } return; } App.Init(); Mutex mutex = new Mutex(true, "mpvnetProcessInstance", out bool isFirst); if ((App.ProcessInstance == "single" || App.ProcessInstance == "queue") && !isFirst) { List <string> files = new List <string>(); files.Add(App.ProcessInstance); foreach (string arg in args) { if (!arg.StartsWith("--") && (arg == "-" || arg.Contains("://") || arg.Contains(":\\") || arg.StartsWith("\\\\"))) { files.Add(arg); } else if (arg == "--queue") { files[0] = "queue"; } } Process[] procs = Process.GetProcessesByName("mpvnet"); for (int i = 0; i < 20; i++) { foreach (Process proc in procs) { if (proc.MainWindowHandle != IntPtr.Zero) { WinAPI.AllowSetForegroundWindow(proc.Id); var data = new WinAPI.COPYDATASTRUCT(); data.lpData = string.Join("\n", files.ToArray()); data.cbData = data.lpData.Length * 2 + 1; WinAPI.SendMessage(proc.MainWindowHandle, 0x004A /*WM_COPYDATA*/, IntPtr.Zero, ref data); mutex.Dispose(); if (App.IsStartedFromTerminal) { WinAPI.FreeConsole(); } return; } } Thread.Sleep(50); } mutex.Dispose(); return; } Application.Run(new MainForm()); if (App.IsStartedFromTerminal) { WinAPI.FreeConsole(); } mutex.Dispose(); } catch (Exception ex) { Msg.ShowException(ex); } }
private static bool IsMouseInClientArea(MouseInput e, WinAPI.Windows.RECT calcRect) { return (calcRect.Left <= (int)e.Point.X && calcRect.Top <= (int)e.Point.Y) && (calcRect.Right >= (int)e.Point.X && calcRect.Bottom >= (int)e.Point.Y); }
public static void Init() { if (running) { bool exist = true; if (Environment.Is64BitOperatingSystem) { if (Process.GetProcessesByName("jkl").Length > 0) { Logging.Log("[JKL] > JKL already running."); } else { exist = false; } } else { if (Process.GetProcessesByName("jklx86").Length > 0) { Logging.Log("[JKL] > JKLx86 already running."); } else { exist = false; } } if (!exist) { Logging.Log("[JKL] > JKL seems closed, restarting..."); running = false; } } if (HWND == IntPtr.Zero) { Logging.Log("[JKL] > Initializing JKL HWND server..."); WNDPROC_DELEGATE = jklWndProc; var wnd_class = new WinAPI.WNDCLASS(); wnd_class.lpszClassName = "_XHIDDEN_HWND_SERVER"; wnd_class.lpfnWndProc = Marshal.GetFunctionPointerForDelegate(WNDPROC_DELEGATE); UInt16 cls_reg = WinAPI.RegisterClassW(ref wnd_class); int last_error = Marshal.GetLastWin32Error(); if (cls_reg == 0 && last_error != 0) { Logging.Log("[JKL] > Could not register window class, for jkl Hidden Server, err: " + last_error, 1); } HWND = WinAPI.CreateWindowExW(0, "_XHIDDEN_HWND_SERVER", "_XHIDDEN_HWND_SERVER", 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } if (!running) { if (jklExist()) { if (Environment.Is64BitOperatingSystem) { Logging.Log("[JKL] > Starting jkl.exe..."); var jkl = new ProcessStartInfo(); jkl.UseShellExecute = true; jkl.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "jkl.exe"); jkl.WorkingDirectory = Path.Combine(Path.GetTempPath()); Process.Start(jkl); } else { Logging.Log("[JKL] > Starting \"jklx86.exe -msg\"..."); var jkl = new ProcessStartInfo(); jkl.UseShellExecute = true; jkl.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "jklx86.exe"); jkl.Arguments = "-msg"; jkl.WorkingDirectory = Path.Combine(Path.GetTempPath()); Process.Start(jkl); } var umsgID = Path.Combine(Path.GetTempPath(), "umsg.id"); var tries = 0; while (!File.Exists(umsgID)) { Thread.Sleep(350); tries++; if (tries > 20) { Logging.Log("[JKL] > Error, umsg.id not found after 20 tries by 350 ms timeout.", 1); Destroy(); break; } } if (tries <= 20) { Logging.Log("[JKL] > umsg.id found, after " + tries + " tries * 350ms timeout."); Logging.Log("[JKL] > Retrieving umsg.id..."); jkluMSG = Convert.ToInt32(File.ReadAllText(umsgID)); File.Delete(umsgID); KMHook.DoLater(() => CycleAllLayouts(Locales.ActiveWindow()), 350); running = true; } } else { Logging.Log("[JKL] > " + jklInfoStr, 1); } Logging.Log("[JKL] > Init done, umsg: [" + jkluMSG + "], JKLXServ: [" + HWND + "]."); } }
public override bool[] UnloadAll(IntPtr[] hModules, IntPtr hProcess) { this.ClearErrors(); IntPtr intPtr = IntPtr.Zero; IntPtr intPtr2 = IntPtr.Zero; IntPtr intPtr3 = IntPtr.Zero; bool[] result; try { uint num = 0u; IntPtr procAddress = WinAPI.GetProcAddress(WinAPI.GetModuleHandleA("kernel32.dll"), "FreeLibrary"); if (procAddress.IsNull()) { throw new Exception("Unable to find necessary function entry points in the remote process"); } intPtr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint)((uint)hModules.Length << 2), 12288, 4); intPtr2 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint)((uint)(hModules.Length + 1) << 2), 12288, 4); intPtr3 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint)StandardInjectionMethod.MULTIUNLOAD_STUB.Length, 12288, 64); if (intPtr.IsNull() || intPtr2.IsNull() || intPtr3.IsNull()) { throw new InvalidOperationException("Unable to allocate memory in the remote process"); } byte[] array = new byte[hModules.Length + 1 << 2]; for (int i = 0; i < hModules.Length; i++) { BitConverter.GetBytes(hModules[i].ToInt32()).CopyTo(array, i << 2); } WinAPI.WriteProcessMemory(hProcess, intPtr2, array, array.Length, out num); byte[] array2 = (byte[])StandardInjectionMethod.MULTIUNLOAD_STUB.Clone(); BitConverter.GetBytes(intPtr2.ToInt32()).CopyTo(array2, 7); BitConverter.GetBytes(intPtr.ToInt32()).CopyTo(array2, 15); BitConverter.GetBytes(procAddress.Subtract(intPtr3.Add(56L)).ToInt32()).CopyTo(array2, 52); if (!WinAPI.WriteProcessMemory(hProcess, intPtr3, array2, array2.Length, out num) || num != (uint)array2.Length) { throw new InvalidOperationException("Unable to write the function stub to the remote process."); } if (WinAPI.RunThread(hProcess, intPtr3, 0u, 1000) == 4294967295u) { throw new InvalidOperationException("Error occurred when running remote function stub."); } byte[] array3 = WinAPI.ReadRemoteMemory(hProcess, intPtr, (uint)((uint)hModules.Length << 2)); if (array3 == null) { throw new Exception("Unable to read results from the remote process."); } bool[] array4 = new bool[hModules.Length]; for (int j = 0; j < array4.Length; j++) { array4[j] = (BitConverter.ToInt32(array3, j << 2) != 0); } result = array4; } catch (Exception lastError) { this.SetLastError(lastError); result = null; } finally { WinAPI.VirtualFreeEx(hProcess, intPtr3, 0, 32768); WinAPI.VirtualFreeEx(hProcess, intPtr, 0, 32768); WinAPI.VirtualFreeEx(hProcess, intPtr2, 0, 32768); } return(result); }
protected virtual IntPtr CreateMultiLoadStub(string[] paths, IntPtr hProcess, out IntPtr pModuleBuffer, uint nullmodule = 0u) { pModuleBuffer = IntPtr.Zero; IntPtr intPtr = IntPtr.Zero; IntPtr result; try { IntPtr moduleHandleA = WinAPI.GetModuleHandleA("kernel32.dll"); IntPtr procAddress = WinAPI.GetProcAddress(moduleHandleA, "LoadLibraryA"); IntPtr procAddress2 = WinAPI.GetProcAddress(moduleHandleA, "GetModuleHandleA"); if (procAddress.IsNull() || procAddress2.IsNull()) { throw new Exception("Unable to find necessary function entry points in the remote process"); } pModuleBuffer = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint)((uint)paths.Length << 2), 12288, 4); IntPtr intPtr2 = WinAPI.CreateRemotePointer(hProcess, Encoding.ASCII.GetBytes(string.Join("\0", paths) + "\0"), 4); if (pModuleBuffer.IsNull() || intPtr2.IsNull()) { throw new InvalidOperationException("Unable to allocate memory in the remote process"); } try { uint num = 0u; byte[] array = new byte[paths.Length << 2]; { BitConverter.GetBytes(nullmodule).CopyTo(array, i << 2); } WinAPI.WriteProcessMemory(hProcess, pModuleBuffer, array, array.Length, out num); byte[] array2 = (byte[])StandardInjectionMethod.MULTILOAD_STUB.Clone(); intPtr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint)array2.Length, 12288, 64); if (intPtr.IsNull()) { throw new InvalidOperationException("Unable to allocate memory in the remote process"); } BitConverter.GetBytes(intPtr2.ToInt32()).CopyTo(array2, 7); BitConverter.GetBytes(paths.Length).CopyTo(array2, 15); BitConverter.GetBytes(pModuleBuffer.ToInt32()).CopyTo(array2, 24); BitConverter.GetBytes(procAddress2.Subtract(intPtr.Add(56L)).ToInt32()).CopyTo(array2, 52); BitConverter.GetBytes(procAddress.Subtract(intPtr.Add(69L)).ToInt32()).CopyTo(array2, 65); if (!WinAPI.WriteProcessMemory(hProcess, intPtr, array2, array2.Length, out num) || num != (uint)array2.Length) { throw new Exception("Error creating the remote function stub."); } result = intPtr; } finally { WinAPI.VirtualFreeEx(hProcess, pModuleBuffer, 0, 32768); WinAPI.VirtualFreeEx(hProcess, intPtr2, 0, 32768); if (!intPtr.IsNull()) { WinAPI.VirtualFreeEx(hProcess, intPtr, 0, 32768); } pModuleBuffer = IntPtr.Zero; } } catch (Exception lastError) { this.SetLastError(lastError); result = IntPtr.Zero; } return(result); }
/// <summary> /// Returns whether the given key went up since the last Update-call /// </summary> /// <param name="key">Key to check</param> /// <returns></returns> public bool KeyWentUp(WinAPI.VirtualKeyShort key) { return KeyWentUp((int) key); }
public static extern bool GetWindowRect(IntPtr hWnd, out WinAPI.RECT lpRect);
public static bool GetKeyDown(WinAPI.VirtualKeyShort key) { return GetKeyDown((int) key); }
/// <summary>This macro is used to create a unique system I/O control code (IOCTL).</summary> /// <param name="deviceType"> /// Defines the type of device for the given IOCTL. /// This parameter can be no bigger then a WORD value. /// The values used by Microsoft are in the range 0-32767 and the values 32768-65535 are reserved for use by OEMs and IHVs. /// </param> /// <param name="function"> /// Defines an action within the device category. /// That function codes 0-2047 are reserved for Microsoft, and 2048-4095 are reserved for OEMs and IHVs. /// The function code can be no larger then 4095. /// </param> /// <param name="method">Defines the method codes for how buffers are passed for I/O and file system controls.</param> /// <param name="access">Defines the access check value for any access.</param> /// <remarks> /// The macro can be used for defining IOCTL and FSCTL function control codes. /// All IOCTLs must be defined this way to ensure that no overlaps occur between Microsoft and OEMs and IHVs. /// </remarks> /// <returns>IO control code</returns> private static UInt32 CTL_CODE(UInt16 deviceType, UInt16 function, WinAPI.METHOD method, WinAPI.FILE_ACCESS access) { return (UInt32)((deviceType << 16) | ((UInt16)access << 14) | (function << 2) | (Byte)method); }
public WorkerCoreStatus[] GetStatus() { // here we have to walk into another process's (fbuildworker) territory to get some text from a list view control var listViewPtr = this.GetChildWindow(0, "SysListView32"); var itemCount = WinAPI.SendMessage(listViewPtr, (int)WinAPI.ListViewMessages.LVM_GETITEMCOUNT, 0, IntPtr.Zero).ToInt32(); var result = new WorkerCoreStatus[itemCount]; // open fbuildworker process var processId = 0u; WinAPI.GetWindowThreadProcessId(listViewPtr, ref processId); var processHandle = WinAPI.OpenProcess( WinAPI.ProcessAccessFlags.VirtualMemoryOperation | WinAPI.ProcessAccessFlags.VirtualMemoryRead | WinAPI.ProcessAccessFlags.VirtualMemoryWrite, false, processId); // allocate memory for text to read var textBufferPtr = WinAPI.VirtualAllocEx( processHandle, IntPtr.Zero, WinAPI.MAX_LVMSTRING, WinAPI.AllocationType.Commit, WinAPI.MemoryProtection.ReadWrite); var lvItem = new WinAPI.LVITEM { mask = (uint)WinAPI.ListViewItemFilters.LVIF_TEXT, cchTextMax = (int)WinAPI.MAX_LVMSTRING, pszText = textBufferPtr }; // marshal the LVITEM structure into unmanaged memory so it can be written into textBufferPtr var lvItemSize = Marshal.SizeOf(lvItem); var lvItemBufferPtr = WinAPI.VirtualAllocEx( processHandle, IntPtr.Zero, (uint)lvItemSize, WinAPI.AllocationType.Commit, WinAPI.MemoryProtection.ReadWrite); var lvItemLocalPtr = Marshal.AllocHGlobal(lvItemSize); var localTextBuffer = new byte[WinAPI.MAX_LVMSTRING]; string GetCellText(int itemId, int subItemId) { lvItem.iItem = itemId; lvItem.iSubItem = subItemId; // write the LVITEM structure to target process's memory Marshal.StructureToPtr(lvItem, lvItemLocalPtr, false); WinAPI.WriteProcessMemory( processHandle, lvItemBufferPtr, lvItemLocalPtr, (uint)lvItemSize, out var _); WinAPI.SendMessage(listViewPtr, (int)WinAPI.ListViewMessages.LVM_GETITEMTEXT, itemId, lvItemBufferPtr); // read the text WinAPI.ReadProcessMemory( processHandle, textBufferPtr, localTextBuffer, (int)WinAPI.MAX_LVMSTRING, out var _); var text = Encoding.Unicode.GetString(localTextBuffer); var zeroIndex = text.IndexOf('\0'); return(zeroIndex < 0 ? text : text.Substring(0, zeroIndex)); } for (var i = 0; i < itemCount; ++i) { var host = GetCellText(i, 1); var status = GetCellText(i, 2); WorkerCoreState state; string workingItem = null; switch (status) { case "Idle": state = WorkerCoreState.Idle; break; case "(Disabled)": state = WorkerCoreState.Disabled; break; default: state = WorkerCoreState.Working; workingItem = status; break; } result[i] = new WorkerCoreStatus(state, host, workingItem); } WinAPI.VirtualFreeEx(processHandle, textBufferPtr, 0, WinAPI.AllocationType.Release); WinAPI.VirtualFreeEx(processHandle, lvItemBufferPtr, 0, WinAPI.AllocationType.Release); Marshal.FreeHGlobal(lvItemLocalPtr); WinAPI.CloseHandle(processHandle); return(result); }
static void Main(string[] args) { UnhandledExceptionHandler.CatchUnhandledExceptions(); Logger = new Logger(); Reader = new Reader(); WindowHandler = new WindowHandler(); UrlMp3Reader = new UrlMp3Reader(); Reader.ReadAsync("Listening stopped."); var hWnd = WinAPI.FindWindow(null, Console.Title); if (hWnd != IntPtr.Zero) { WinAPI.ShowWindow(hWnd, 0); } commands = new List <ICommand>(); var commandType = typeof(ICommand); var basic_commands = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(assembly => assembly.GetTypes()) .Where(type => !type.IsInterface && commandType.IsAssignableFrom(type)); foreach (var basic_command in basic_commands) { var needAutoResetEventType = typeof(INeedAutoResetEvent); var command = needAutoResetEventType.IsAssignableFrom(basic_command) ? (ICommand)Activator.CreateInstance(basic_command, new object[] { exitEvent }) : (ICommand)Activator.CreateInstance(basic_command); commands.Add(command); } SpeechRecognitionEngine.SpeechRecognized += SpeechRecognitionEngineOnSpeechRecognized; try { SpeechRecognitionEngine.SetInputToDefaultAudioDevice(); } catch (PlatformNotSupportedException) { ErrorBox.Show("Requirement not found", "Please install recognition engine: https://www.microsoft.com/en-us/download/confirmation.aspx?id=27225, https://www.microsoft.com/en-us/download/details.aspx?id=27224"); return; } var words = new Choices(); foreach (var command_names in commands.SelectMany(command => command.CommandName)) { words.Add(command_names); } var grammar_builder = new GrammarBuilder(words) { Culture = SpeechRecognitionEngine.RecognizerInfo.Culture }; Commands = new Grammar(grammar_builder); SpeechRecognitionEngine.LoadGrammar(Commands); SpeechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple); exitEvent.WaitOne(); SpeechRecognitionEngine.RecognizeAsyncCancel(); Reader.Read("See you later.", "Good bye!", "Bye bye!", "Bye for now!", "Bye!", "So long!"); }
/// <summary>This macro is used to create a unique system I/O control code (IOCTL).</summary> /// <param name="deviceType"> /// Defines the type of device for the given IOCTL. /// This parameter can be no bigger then a WORD value. /// The values used by Microsoft are in the range 0-32767 and the values 32768-65535 are reserved for use by OEMs and IHVs. /// </param> /// <param name="function"> /// Defines an action within the device category. /// That function codes 0-2047 are reserved for Microsoft, and 2048-4095 are reserved for OEMs and IHVs. /// The function code can be no larger then 4095. /// </param> /// <param name="access">Defines the access check value for any access.</param> /// <remarks> /// The macro can be used for defining IOCTL and FSCTL function control codes. /// All IOCTLs must be defined this way to ensure that no overlaps occur between Microsoft and OEMs and IHVs. /// </remarks> /// <returns>IO control code</returns> private static UInt32 CTL_CODE(UInt16 deviceType, UInt16 function, WinAPI.FILE_ACCESS access) { return CTL_CODE(deviceType, function, WinAPI.METHOD.BUFFERED, access); }
private void Button_ImportStat_Click(object sender, RoutedEventArgs e) { AudioUtil.ClickSound(); if (!ProcessUtil.IsAppRun("GTAHax")) { ProcessUtil.OpenProcess("GTAHax", false); } Task.Run(() => { bool isRun = false; do { if (ProcessUtil.IsAppRun("GTAHax")) { isRun = true; var pGTAHax = Process.GetProcessesByName("GTAHax").ToList()[0]; bool isShow = false; do { IntPtr Menu_handle = pGTAHax.MainWindowHandle; IntPtr child_handle = WinAPI.FindWindowEx(Menu_handle, IntPtr.Zero, "Static", null); child_handle = WinAPI.FindWindowEx(Menu_handle, child_handle, "Static", null); child_handle = WinAPI.FindWindowEx(Menu_handle, child_handle, "Static", null); child_handle = WinAPI.FindWindowEx(Menu_handle, child_handle, "Static", null); child_handle = WinAPI.FindWindowEx(Menu_handle, child_handle, "Edit", null); child_handle = WinAPI.FindWindowEx(Menu_handle, child_handle, "Edit", null); child_handle = WinAPI.FindWindowEx(Menu_handle, child_handle, "Button", null); child_handle = WinAPI.FindWindowEx(Menu_handle, child_handle, "Button", null); child_handle = WinAPI.FindWindowEx(Menu_handle, child_handle, "Button", null); if (child_handle != IntPtr.Zero) { isShow = true; WinAPI.SendMessage(child_handle, WinAPI.WM_LBUTTONDOWN, IntPtr.Zero, null); WinAPI.SendMessage(child_handle, WinAPI.WM_LBUTTONUP, IntPtr.Zero, null); MsgBoxUtil.Information("导入到GTAHax成功!代码正在执行,请返回GTAHax和GTA5游戏查看\n\n如果未执行,请重新点击\"导入GTAHax\"\n如果执行成功游戏内会出现大受好评奖章"); } else { isShow = false; } Task.Delay(100).Wait(); } while (!isShow); } else { isRun = false; } Task.Delay(100).Wait(); } while (!isRun); }); }
private bool IsKeyPressed(WinAPI.VK vk) { return pressedKeys[(int)vk] == 0x80; }
public FocusTargetWidget() { View = this; InitializeComponent(); View.SourceInitialized += delegate { WinAPI.ToggleClickThrough(this); }; }
private Vector3 ReadAngle(IntPtr handle, int address) { byte[] data = WinAPI.ReadMemory(handle, address, 12); return(new Vector3(BitConverter.ToSingle(data, 0), BitConverter.ToSingle(data, 4), BitConverter.ToSingle(data, 8))); }
public override void OnUpdaterTick() { if (Program.GameImplementation == null) { return; } if (Program.GameController == null) { return; } if (!Program.GameController.IsGameRunning) { return; } if (!Program.GameController.IsInGame) { return; } CSGOImplementation csgo = ((CSGOImplementation)Program.GameImplementation); IntPtr handle = Program.GameImplementation.GameController.Process.Handle; //Get addresses if (!updatedOffsets) { FindOffsets(); } entityListAddress = dllClientAddress + GameOffsets.CL_ENTITY_LIST; localAddress = WinAPI.ReadInt32(handle, dllClientAddress + GameOffsets.CL_LOCAL_BASE_ENTITY); radarAddress = WinAPI.ReadInt32(handle, dllClientAddress + GameOffsets.CL_RADAR_BASE); radarAddress = WinAPI.ReadInt32(handle, radarAddress + GameOffsets.CL_RADAR_OFFSET); //B658BEC scoreBoardAddress = WinAPI.ReadInt32(handle, dllClientAddress + GameOffsets.CL_SCRBRD_BASE); enginePointer = WinAPI.ReadInt32(handle, dllEngineAddress + GameOffsets.EN_ENGINE_POINTER); csgo.SignOnState = (SignOnState)WinAPI.ReadInt32(handle, enginePointer + GameOffsets.EN_SIGNONSTATE); if (csgo.SignOnState < SignOnState.SIGNONSTATE_PRESPAWN || csgo.SignOnState > SignOnState.SIGNONSTATE_FULL) { return; } //General csgo.ScreenSize = new SharpDX.Size2(Program.GameController.WindowArea.Width, Program.GameController.WindowArea.Height); int targetIndex = WinAPI.ReadInt32(handle, localAddress + GameOffsets.CL_LOCAL_CROSSHAIR_TARGET); Matrix4x4 viewMatrix = Matrix4x4.ReadMatrix(handle, dllClientAddress + GameOffsets.CL_LOCAL_VIEWMATRIX); bool c4Planted = false; //Refresh players if (Environment.TickCount - newPlayers >= 1000) { newPlayers = Environment.TickCount; csgo.Players = null; csgo.Entities = null; } //Read scrbrd-data byte[] scrbrdData = WinAPI.ReadMemory(handle, scoreBoardAddress, 0x1C38); if (csgo.ScrBrdArmor == null) { csgo.ScrBrdArmor = new int[MAX_PLAYERS]; } if (csgo.ScrBrdAssists == null) { csgo.ScrBrdAssists = new int[MAX_PLAYERS]; } if (csgo.ScrBrdDeaths == null) { csgo.ScrBrdDeaths = new int[MAX_PLAYERS]; } if (csgo.ScrBrdHealth == null) { csgo.ScrBrdHealth = new int[MAX_PLAYERS]; } if (csgo.ScrBrdKills == null) { csgo.ScrBrdKills = new int[MAX_PLAYERS]; } if (csgo.ScrBrdScore == null) { csgo.ScrBrdScore = new int[MAX_PLAYERS]; } if (csgo.ScrBrdRanks == null) { csgo.ScrBrdRanks = new int[MAX_PLAYERS]; } if (csgo.ScrBrdWins == null) { csgo.ScrBrdWins = new int[MAX_PLAYERS]; } for (int i = 0; i < MAX_PLAYERS; i++) { csgo.ScrBrdArmor[i] = BitConverter.ToInt32(scrbrdData, GameOffsets.CL_SCRBRD_ARMOR + 4 * i); csgo.ScrBrdAssists[i] = BitConverter.ToInt32(scrbrdData, GameOffsets.CL_SCRBRD_ASSISTS + 4 * i); csgo.ScrBrdDeaths[i] = BitConverter.ToInt32(scrbrdData, GameOffsets.CL_SCRBRD_DEATHS + 4 * i); csgo.ScrBrdHealth[i] = BitConverter.ToInt32(scrbrdData, GameOffsets.CL_SCRBRD_HEALTH + 4 * i); csgo.ScrBrdKills[i] = BitConverter.ToInt32(scrbrdData, GameOffsets.CL_SCRBRD_KILLS + 4 * i); csgo.ScrBrdScore[i] = BitConverter.ToInt32(scrbrdData, GameOffsets.CL_SCRBRD_SCORE + 4 * i); csgo.ScrBrdRanks[i] = BitConverter.ToInt32(scrbrdData, GameOffsets.CL_SCRBRD_RANKING + 4 * i); csgo.ScrBrdWins[i] = BitConverter.ToInt32(scrbrdData, GameOffsets.CL_SCRBRD_WINS + 4 * i); } //Read players & entities if (csgo.Players == null) { csgo.Players = new Player[MAX_PLAYERS]; } if (csgo.Entities == null) { csgo.Entities = new Entity[MAX_ENTITIES - MAX_PLAYERS]; } int maxIndex = 2048;// = WinAPI.ReadInt32(handle, entityListAddress + 0x4); //maxIndex -= entityListAddress; //maxIndex /= GameOffsets.CL_ENTITY_SIZE; byte[] entityList = WinAPI.ReadMemory(handle, entityListAddress, maxIndex * GameOffsets.CL_ENTITY_SIZE); for (int i = 0; i < maxIndex; i++) { try { int address = BitConverter.ToInt32(entityList, GameOffsets.CL_ENTITY_SIZE * i); if (address != 0) { if (i < 64) { if (csgo.Players[i] == null) { csgo.Players[i] = new Player(address, radarAddress + GameOffsets.CL_RADAR_SIZE * i, i + 1); } else { csgo.Players[i].Update(address, radarAddress + GameOffsets.CL_RADAR_SIZE * i, i + 1); } } else { if (csgo.Entities[i - csgo.Players.Length] == null) { csgo.Entities[i - csgo.Players.Length] = new Entity(address, radarAddress, i); } else { csgo.Entities[i - csgo.Players.Length].Update(address, radarAddress, i); } //if (!entityClasses.ContainsKey(csgo.Entities[i - csgo.Players.Length].ClassIDInt)) // entityClasses.Add(csgo.Entities[i - csgo.Players.Length].ClassIDInt, csgo.Entities[i - csgo.Players.Length].Name); if (!csgo.Entities[i - csgo.Players.Length].IsValid()) { csgo.Entities[i - csgo.Players.Length] = null; } else if (csgo.Entities[i - csgo.Players.Length].ClassID == ClassID.PlantedC4) { c4Planted = true; } } } } catch { } } //Get weaponID long weaponHandle = WinAPI.ReadInt32(handle, localAddress + GameOffsets.CL_LOCAL_ACTIVE_WEAPON); long weaponIDFirst = weaponHandle & 0xFFF; long weaponBase = WinAPI.ReadInt32(handle, entityListAddress + ((weaponIDFirst - 1) * 0x10)); int weaponID = WinAPI.ReadInt32(handle, weaponBase + GameOffsets.CL_LOCAL_WEAPON_ID); float accuracyPenality = WinAPI.ReadFloat(handle, weaponBase + GameOffsets.CL_LOCAL_WEAPON_ACCURACYPENALITY); //int weaponShotsFired = WinAPI.ReadInt32(handle, localPlayer + GameOffsets.CL_LOCAL_WEAPON_SHOTS_FIRED); //Debug.WriteLine(accuracyPenality); ZoomLevel zoom = (ZoomLevel)WinAPI.ReadMemory(handle, weaponBase + GameOffsets.CL_LOCAL_WEAPON_ZOOM, 1)[0]; bool isReloading = WinAPI.ReadMemory(handle, weaponBase + GameOffsets.CL_LOCAL_WEAPON_RELOAD, 1)[0] == 1; //Get clips long clip1 = WinAPI.ReadInt32(handle, dllClientAddress + GameOffsets.CL_RADAR_BASE); long clip2 = WinAPI.ReadInt32(handle, clip1 + GameOffsets.CL_WEAPON_OFFSET); int weaponClip1 = WinAPI.ReadInt32(handle, clip2 + GameOffsets.CL_WEAPON_AMMO_PRIM); int weaponClip2 = WinAPI.ReadInt32(handle, clip2 + GameOffsets.CL_WEAPON_AMMO_SEC); //Angles csgo.ViewAngles = ReadAngle(handle, enginePointer + GameOffsets.EN_VIEWANGLE_X); csgo.ViewOffset = ReadAngle(handle, localAddress + GameOffsets.CL_LOCAL_VIEWOFFSET); //overwrite data csgo.LocalPlayer = FindLocalPlayer(csgo.Players, localAddress); if (targetIndex > 0 && targetIndex <= 64) { csgo.TargetPlayer = csgo.Players[targetIndex - 1]; } else { csgo.TargetPlayer = null; } csgo.TargetIndex = targetIndex; if (csgo.C4Planted != c4Planted) { csgo.C4Planted = c4Planted; csgo.C4PlantTime = Environment.TickCount; } csgo.AccuracyPenality = accuracyPenality; csgo.C4Timer = WinAPI.ReadFloat(handle, dllClientAddress + GameOffsets.CL_NETVAR_MPC4TIMER); csgo.ServerMap = WinAPI.ReadString(handle, dllClientAddress + GameOffsets.CL_SRV_BASE + GameOffsets.CL_SRV_MAP, 32, Encoding.ASCII); csgo.ServerIP = WinAPI.ReadString(handle, dllClientAddress + GameOffsets.CL_SRV_BASE + GameOffsets.CL_SRV_IP, 32, Encoding.ASCII); csgo.ServerName = WinAPI.ReadString(handle, dllClientAddress + GameOffsets.CL_SRV_BASE + GameOffsets.CL_SRV_Name, 32, Encoding.ASCII); csgo.IsReloading = isReloading; csgo.IsShooting = WinAPI.ReadMemory(handle, dllClientAddress + GameOffsets.CL_LOCAL_BUTTONS_ATTACK, 1)[0] == 5; csgo.ViewMatrix = viewMatrix; csgo.WeaponClip1 = weaponClip1; csgo.WeaponClip2 = weaponClip2; csgo.WeaponFireRate = WeaponHandler.Instance.GetWeaponFireRate(weaponID); csgo.WeaponName = WeaponHandler.Instance.GetWeaponName(weaponID); csgo.WeaponType = WeaponHandler.Instance.GetWeaponType(weaponID); csgo.FlashMaxAlpha = WinAPI.ReadFloat(handle, localAddress + GameOffsets.CL_LOCAL_FLASH_MAX_ALPHA); csgo.FlashMaxDuration = WinAPI.ReadFloat(handle, localAddress + GameOffsets.CL_LOCAL_FLASH_MAX_DURATION); //csgo.WeaponShotsFired = weaponShotsFired; csgo.ZoomLevel = zoom; csgo.FirstPersonSpectator = false; csgo.Spectators.Clear(); if (csgo.LocalPlayer != null) { foreach (Player player in csgo.Players) { if (player == null) { continue; } if (player.SpectatorTarget == csgo.LocalPlayer.Index) { csgo.Spectators.Add(player); if (player.SpectatorView == Data.Enums.SpectatorView.Ego) { csgo.FirstPersonSpectator = true; } } } } if (csgo.LocalPlayer == null) { return; } if (csgo.GetValue <YesNo>("miscBunnyHopEnabled") == YesNo.Yes) { if (WinAPI.GetKeyDown(System.Windows.Forms.Keys.Space)) { int addrJmp = dllClientAddress + GameOffsets.CL_LOCAL_BUTTONS_JUMP; //Test stuff if (csgo.LocalPlayer.State == PlayerState.Jump)// && WinAPI.GetKeyDown(System.Windows.Forms.Keys.Up)) { byte[] buffer = BitConverter.GetBytes(4); WinAPI.WriteMemory(handle, addrJmp, buffer, buffer.Length); } else if (csgo.LocalPlayer.State == PlayerState.Stand) { byte[] buffer2 = BitConverter.GetBytes(5); WinAPI.WriteMemory(handle, addrJmp, buffer2, buffer2.Length); } } } if (csgo.GetValue <YesNo>("miscAutoPistolEnabled") == YesNo.Yes) { if (WinAPI.GetKeyDown(System.Windows.Forms.Keys.LButton) && csgo.WeaponType == WeaponType.Pistol) { IntPtr bytesWritten = IntPtr.Zero; int addrJmp = dllClientAddress + GameOffsets.CL_LOCAL_BUTTONS_ATTACK; int val = WinAPI.ReadInt32(handle, addrJmp); if (val == 0) { WinAPI.WriteMemory(handle, addrJmp, BitConverter.GetBytes(1), 4); } else { WinAPI.WriteMemory(handle, addrJmp, BitConverter.GetBytes(0), 4); } } } //Glow-stuff int glowAddr = WinAPI.ReadInt32(handle, dllClientAddress + GameOffsets.CL_GLOWMANAGER); int objectCount = WinAPI.ReadInt32(handle, dllClientAddress + GameOffsets.CL_GLOWMANAGER + 4); GlowObjectDefinition[] glowObjects = new GlowObjectDefinition[objectCount]; byte[] glowObjectData = WinAPI.ReadMemory(handle, glowAddr, GlowObjectDefinition.GetSize() * objectCount); for (int i = 0; i < glowObjects.Length; i++) { byte[] subData = new byte[GlowObjectDefinition.GetSize()]; Array.Copy(glowObjectData, GlowObjectDefinition.GetSize() * i, subData, 0, GlowObjectDefinition.GetSize()); glowObjects[i] = WinAPI.GetStructure <GlowObjectDefinition>(subData); } csgo.GlowObjects = glowObjects; tick++; }
public static MouseInput CreateFrom(WinAPI.WM wm, Mubox.WinAPI.WindowHook.MSLLHOOKSTRUCT hookStruct) { return new MouseInput { WM = wm, Point = new System.Windows.Point(hookStruct.pt.X, hookStruct.pt.Y), MouseData = hookStruct.mouseData, Time = hookStruct.time, }; }
public MouseEventExtArgs(MouseButtons b, int clickcount, WinAPI.POINT point, int delta) : base(b, clickcount, point.X, point.Y, delta) { }
private void TriggerToggleOrHold(WinAPI.VirtualKeyShort triggerKey, bool triggerToggle, bool triggerHold) { if (triggerToggle) { if (Program.KeyUtils.KeyWentUp(triggerKey)) TriggerbotActive = !TriggerbotActive; } else if (triggerHold) { TriggerbotActive = Program.KeyUtils.KeyIsDown(triggerKey); } if (TriggerbotActive) Triggerbot(); }
public void Remove(WinAPI.VK inputKey) { base.BaseRemove(inputKey); }
private static bool IsKeyPressed(WinAPI.VK vk) { return pressedKeys[(int)vk]; }
public bool TryGetKeySetting(WinAPI.VK vk, out KeySetting keySetting) { keySetting = base.BaseGet(vk) as KeySetting; return keySetting != null; }
/// <summary> /// <para>Updates 'pressed keys', returns true if pressed keys was updated.</para> /// </summary> /// <param name="hookStruct"></param> /// <returns>True if key state has/is changed due to this event.</returns> private static bool UpdatePressedKeys(WinAPI.WindowHook.KBDLLHOOKSTRUCT hookStruct) { var result = false; if (WinAPI.WindowHook.LLKHF.UP != (hookStruct.flags & WinAPI.WindowHook.LLKHF.UP)) { if (!IsKeyPressed(hookStruct.vkCode)) { result = true; pressedKeys[(int)hookStruct.vkCode] = true; } } else { if (IsKeyPressed(hookStruct.vkCode)) { result = true; pressedKeys[(int)hookStruct.vkCode] = false; } } return result; }
private void SetLocation(WinAPI.POINT location) { this.Left = location.x; this.Top = location.y; }