static void ReOpener() { int i = 1; while (true) { Thread.Sleep(10000); if (died) { if (!opening) { try { Log.ApiError($"Trying to reconnect for the {i++}-th time"); VK.Alert("АХТУНГ, БАЛАНСЕР УПАЛ"); AllocSocket(); OpenSocket(); } catch (Exception ex) { Log.Error("Some error occured. Message: " + ex.Message + "\nTrace: " + ex.StackTrace); } } else { AllocSocket(); OpenSocket(); } } } }
private void BackgroundCheck() { #if DEBUG logger.Warn("Background pinger is disabled in debug mode."); #else Thread.Sleep(60000); while (true) { try { foreach (BotConfig bot in coreConfig.Bots) { if (!PingedRecently(bot.Username) && IsPrimetime()) { logger.Warn($"Бот {bot.Username} давно не пинговал, видимо, он умер."); VK.Alert($"Бот {bot.Username} давно не пинговал, видимо, он умер."); } } } catch { } Thread.Sleep(60000); ReloadConfig(); } #endif }
/// <summary> /// Авторизация бота через LongPollApi /// </summary> /// <param name="token">Токен</param> private void Authorize(string token) { VK.Authorize(new ApiAuthParams() { AccessToken = token }); }
public SystemHotkey(VK vk, RegisterHotKeyModifiers vk_md) { m_Window.ProcessMessage += new MessageEventHandler(MessageEvent); Virtual_key = (int)vk; vk_mod = (int)vk_md; RegisterHotKey += new RegisterHotKeyDelegate(this.RegiterType); }
// Use this for initialization void Start() { var vk = new VK(); /* * string data = "" + * "{\"response\":{\"count\":103,\"items\":[9942899,12902483,75334099,192528,22369413,6775719,12706737,6155619,4432284,355358,98679916,154187478,266417848,9154318,122130877,93454848,463897,31242453,116369290,8263566,1688087,16725465,2268730,5500129,6328868,21102453,49846973,18441298,21797287,30211521,4195380,431188,10166912,12536599,1513665,50524012,2419570,24477517,106732852,5590642,115472802,10020691,565852,33586925,3723820,216822197,795150,1217893,1864327,2282498,4504596,4667984,4800098,5240342,5332964,6177608,6810594,6826797,11456472,11516336,11910293,12912522,13186453,13505307,13531761,16139012,16868053,17819110,21332751,22362278,23197808,24984763,39492718,42457047,56016303,58608660,64822990,73603643,119419700,153575419,181333705,185720047,200209780,133366415,19609215,29142564,182668879,5675878,5727738,6147130,6351506,8192451,8499689,35381128,47779979,56510169,61716100,67332198,69431747,112763313,136204575,156657887,173583682]}}" * ; * * var a = vk.parseFriendsShortly(data); * * return; */ vk.DoLogIn((successAuth) => { Debug.LogWarning("====================> VK.Login: "******"Testing mobile app", true, success => { Debug.LogWarning("====================> VK.SendToWall: " + success); }); vk.GetShortFriendList((success, friends) => { Debug.LogWarning("====================> VK.GetShortFriendList: " + success); foreach (var fr in friends) { Debug.LogWarning("FriendID: " + fr.id); } }); } }); }
public unsafe VulkanPhysicalDevice[] GetPhysicalDevices(Predicate <VulkanPhysicalDevice>?suitability) { suitability ??= _ => true; uint deviceCount = 0u; VK.EnumeratePhysicalDevices(_VKInstance, &deviceCount, Span <PhysicalDevice> .Empty); Span <PhysicalDevice> physicalDevices = stackalloc PhysicalDevice[(int)deviceCount]; VK.EnumeratePhysicalDevices(_VKInstance, &deviceCount, physicalDevices); VulkanPhysicalDevice[] tempSuitable = ArrayPool <VulkanPhysicalDevice> .Shared.Rent((int)deviceCount); int index = 0; foreach (PhysicalDevice physicalDevice in physicalDevices) { VulkanPhysicalDevice vulkanPhysicalDevice = new VulkanPhysicalDevice(VK, new VulkanContext { Instance = this }, physicalDevice); if (suitability(vulkanPhysicalDevice)) { tempSuitable[index] = vulkanPhysicalDevice; index += 1; } } VulkanPhysicalDevice[] finalSuitable = tempSuitable[..index];
public static void SendKey(VK key) { SetForegroundWindow(Form1.m_captureProcess.Process.MainWindowHandle); INPUT2[] input = new INPUT2[] { new INPUT2() { type = InputType.INPUT_KEYBOARD, ki = new KEYBDINPUT { wVk = 0, wScan = ScanCode.F5, dwFlags = KEYEVENTF.KEYEVENTF_SCANCODE, dwExtraInfo = null, time = 0 } }, new INPUT2() { type = InputType.INPUT_KEYBOARD, ki = new KEYBDINPUT { wVk = 0, wScan = ScanCode.F5, dwFlags = KEYEVENTF.KEYEVENTF_SCANCODE | KEYEVENTF.KEYEVENTF_KEYUP, dwExtraInfo = null, time = 0 } } }; SendInput(input.Length, input, Marshal.SizeOf(typeof(INPUT))); }
public void DoKeyboard(VK key, KEYEVENT keyEvent) { if (IntPtr.Size < 8) { INPUT[] structInputs = new INPUT[1]; structInputs[0].type = INPUT_KEYBOARD; structInputs[0].ki.wScan = 0; structInputs[0].ki.time = 0; structInputs[0].ki.dwFlags = (uint)keyEvent; structInputs[0].ki.dwExtraInfo = IntPtr.Zero; structInputs[0].ki.wVk = (ushort)key; SendInput(1, structInputs, Marshal.SizeOf(typeof(INPUT))); } else { INPUT64[] structInputs = new INPUT64[1]; structInputs[0].type = INPUT_KEYBOARD; structInputs[0].ki.wScan = 0; structInputs[0].ki.time = 0; structInputs[0].ki.dwFlags = (uint)keyEvent; structInputs[0].ki.dwExtraInfo = IntPtr.Zero; structInputs[0].ki.wVk = (ushort)key; SendInput64(1, structInputs, Marshal.SizeOf(typeof(INPUT64))); } }
private void HandleKey(string Keys, VK VirtualKey, Key Scancode, bool Pressed) { if (!Base.TheBox && Keys.Length < 2) { BoxSwitch.HandleKey(Keys, VirtualKey, Pressed); return; } if (!Pressed) { return; } var special = new Key[] { Key.PageUp, Key.PageDown, Key.Home, Key.End, Key.Insert, Key.Delete, Key.Back, Key.Left, Key.Right, Key.Up, Key.Down, Key.F1, Key.F2, Key.F3, Key.F4, Key.F5, Key.F6, Key.F7, Key.F8, Key.F9, Key.F10, Key.F11, Key.F12, Key.Escape }; if (special.Contains(Scancode)) { CurrentReceiver.SpecialKey(VirtualKey); return; } foreach (var key in Keys) { CurrentReceiver.PushKey(key); } }
void CreateImageViews() { if (swapchainImageViews != null) { foreach (var iv in swapchainImageViews) { VK.DestroyImageView(device, iv, alloc); } } swapchainImageViews = new List <VkImageView>(swapchainImages.Count); foreach (var image in swapchainImages) { var info = new VkImageViewCreateInfo(); info.sType = CSGL.Vulkan.VkStructureType.ImageViewCreateInfo; info.image = image; info.viewType = CSGL.Vulkan.VkImageViewType._2D; info.format = swapchainImageFormat; info.components.r = CSGL.Vulkan.VkComponentSwizzle.Identity; info.components.g = CSGL.Vulkan.VkComponentSwizzle.Identity; info.components.b = CSGL.Vulkan.VkComponentSwizzle.Identity; info.components.a = CSGL.Vulkan.VkComponentSwizzle.Identity; info.subresourceRange.aspectMask = CSGL.Vulkan.VkImageAspectFlags.ColorBit; info.subresourceRange.baseMipLevel = 0; info.subresourceRange.levelCount = 1; info.subresourceRange.baseArrayLayer = 0; info.subresourceRange.layerCount = 1; VkImageView temp; var result = VK.CreateImageView(device, ref info, alloc, out temp); swapchainImageViews.Add(temp); } }
void PickQueues() { uint count = 0; VK.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, ref count, IntPtr.Zero); var queues = new NativeArray <VkQueueFamilyProperties>(count); VK.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, ref count, queues.Address); int g = -1; int p = -1; for (int i = 0; i < count; i++) { if (g == -1 && queues[i].queueCount > 0 && (queues[i].queueFlags & CSGL.Vulkan.VkQueueFlags.GraphicsBit) != 0) { g = i; } bool support; getPhysicalDeviceSurfaceSupport(physicalDevice, (uint)i, surface, out support); if (p == -1 && queues[i].queueCount > 0 && support) { p = i; } } graphicsIndex = (uint)g; presentIndex = (uint)p; queues.Dispose(); }
public static void SendKeyPress(VK key) { int cbSize = Marshal.SizeOf(new INPUT()); INPUT[] structInput = new INPUT[1]; structInput[0] = new INPUT(); structInput[0].type = INPUT_KEYBOARD; structInput[0].mkhi.ki.wScan = 0; structInput[0].mkhi.ki.time = 0; structInput[0].mkhi.ki.dwFlags = 0; structInput[0].mkhi.ki.dwExtraInfo = IntPtr.Zero; ushort x = (ushort)key; // Key down the actual key-code structInput[0].mkhi.ki.dwFlags = KEYEVENTF_KEYDOWN; structInput[0].mkhi.ki.wVk = (ushort)key; if ((x >= 33 && x <= 46) || (x >= 91 && x <= 93)) { structInput[0].mkhi.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; } SendInput(1, ref structInput[0], cbSize); // Key up the actual key-code structInput[0].mkhi.ki.dwFlags = KEYEVENTF_KEYUP; structInput[0].mkhi.ki.wVk = (ushort)key; structInput[0].mkhi.ki.time = 0; if ((x >= 33 && x <= 46) || (x >= 91 && x <= 93)) { structInput[0].mkhi.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; } SendInput((uint)1, ref structInput[0], cbSize); }
void CreateFramebuffers() { if (swapchainFramebuffers != null) { foreach (var fb in swapchainFramebuffers) { VK.DestroyFramebuffer(device, fb, alloc); } } swapchainFramebuffers = new List <VkFramebuffer>(swapchainImageViews.Count); for (int i = 0; i < swapchainImageViews.Count; i++) { var attachments = new Native <VkImageView>(swapchainImageViews[i]); var info = new VkFramebufferCreateInfo(); info.sType = CSGL.Vulkan.VkStructureType.FramebufferCreateInfo; info.renderPass = renderPass; info.attachmentCount = 1; info.pAttachments = attachments.Address; info.width = swapchainExtent.width; info.height = swapchainExtent.height; info.layers = 1; VkFramebuffer temp; var result = VK.CreateFramebuffer(device, ref info, alloc, out temp); swapchainFramebuffers.Add(temp); attachments.Dispose(); } }
private static void ShellKeyCombo(VK wVk_1, VK wVk_2) { INPUT[] inputs = new INPUT[4]; inputs[0].type = INPUT_KEYBOARD; inputs[0].mkhi.ki.time = 0; inputs[0].mkhi.ki.wScan = 0; inputs[0].mkhi.ki.dwExtraInfo = GetMessageExtraInfo(); inputs[0].mkhi.ki.wVk = (ushort)wVk_1; inputs[0].mkhi.ki.dwFlags = 0; inputs[1].type = INPUT_KEYBOARD; inputs[1].mkhi.ki.wScan = 0; inputs[1].mkhi.ki.dwExtraInfo = GetMessageExtraInfo(); inputs[1].mkhi.ki.wVk = (ushort)wVk_2; inputs[1].mkhi.ki.dwFlags = 0; inputs[2].type = INPUT_KEYBOARD; inputs[2].mkhi.ki.wScan = 0; inputs[2].mkhi.ki.dwExtraInfo = GetMessageExtraInfo(); inputs[2].mkhi.ki.wVk = (ushort)wVk_2; inputs[2].mkhi.ki.dwFlags = KEYEVENTF_KEYUP; inputs[3].type = INPUT_KEYBOARD; inputs[3].mkhi.ki.wScan = 0; inputs[3].mkhi.ki.dwExtraInfo = GetMessageExtraInfo(); inputs[3].mkhi.ki.wVk = (ushort)wVk_1; inputs[3].mkhi.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(4, inputs, Marshal.SizeOf(typeof(INPUT))); }
internal static Key VkToKey(VK vk, SC sc, LLKHF flags, bool has_shift, bool has_altgr, bool has_capslock) { byte[] keystate = new byte[256]; NativeMethods.GetKeyboardState(keystate); keystate[(int)VK.SHIFT] = (byte)(has_shift ? 0x80 : 0x00); keystate[(int)VK.CONTROL] = (byte)(has_altgr ? 0x80 : 0x00); keystate[(int)VK.MENU] = (byte)(has_altgr ? 0x80 : 0x00); keystate[(int)VK.CAPITAL] = (byte)(has_capslock ? 0x01 : 0x00); // These two calls must be done together and in this order. string str_if_normal = VkToUnicode(vk, sc, keystate, flags); string str_if_dead = VkToUnicode(VK.SPACE); // This indicates that vk was a dead key if (str_if_dead != "" && str_if_dead != " ") { return(new Key(str_if_dead)); } // Special case: we don't consider characters such as Esc as printable // otherwise they are not properly serialised in the config file. if (str_if_normal == "" || str_if_normal[0] < ' ') { return(new Key(vk)); } return(new Key(str_if_normal)); }
public void LogOut() { PlayerPrefs.DeleteKey("refresh_token_gosha"); PlayerPrefs.DeleteKey("refresh_expires_in_gosha"); PlayerPrefs.DeleteKey("provider_gosha"); PlayerPrefs.DeleteKey("CurrentSuit"); PlayerPrefs.DeleteKey("token_gosha"); PlayerPrefs.DeleteKey("token_expires_in_gosha"); PlayerController.Instance.TakeOffSuits(); OneSignal.SetSubscription(false); FB.LogOut(); if (OK.IsInitialized) { OK.Logout(); } VK.LogOut(); Headers = new List <Header>(); userToken = null; User = new UserInfoModel(); LocalUser = true; Canvaser.Instance.SetAllIceCreams(User.IceCream); Canvaser.Instance.SetNotifications(User); GameController.Instance.ResetBonusesTime(); Canvaser.Instance.SBonuses.ResetStartBonuses(); }
static void SendKeyUp(VK sendEvent) { IntPtr winHandle = NativeMethods.FindWindowByCaption(IntPtr.Zero, "Windows Media Center"); NativeMethods.SafeSendMessage(winHandle, NativeMethods.WM_KEYUP, new IntPtr((int)sendEvent), IntPtr.Zero); //object foo = new object(); //NativeMethods.SafePostMessage(new HandleRef(foo, winHandle), NativeMethods.WM_KEYUP, new IntPtr((int)sendEvent), IntPtr.Zero); return; uint intReturn; // ersin was here! NativeMethods.INPUT structInput; structInput = new NativeMethods.INPUT(); structInput.type = NativeMethods.INPUT_KEYBOARD; // Key down shift, ctrl, and/or alt structInput.ki.wScan = 0; structInput.ki.time = 0; structInput.ki.dwExtraInfo = NativeMethods.GetMessageExtraInfo(); structInput.ki.wVk = (ushort)sendEvent; structInput.ki.dwFlags = NativeMethods.KEYEVENTF_KEYUP; intReturn = NativeMethods.SendInput(1, ref structInput, Marshal.SizeOf(structInput)); Debug.Print("SENDKEYUP: " + intReturn.ToString()); }
public static void Load <T>(ref T del, VkDevice device) { var command = GetCommand <T>(); var native = Interop.GetUTF8(command); IntPtr ptr = VK.GetDeviceProcAddr(device, native); del = Marshal.GetDelegateForFunctionPointer <T>(ptr); }
public static string GetKeyName(this VK k) { if (namedKeys.ContainsKey(k)) { return(namedKeys[k]); } return(k.ToString()); }
/// <summary> /// Sequentially press keys one by one /// </summary> /// <param name="virtualKeyCode"></param> public static void KeyPress(VK virtualKeyCode) { INPUT[] input = new INPUT[2]; InputDataFactory(ref input[0], virtualKeyCode); WinAPI.SendInput(1, input, Marshal.SizeOf(typeof(INPUT))); InputDataFactory(ref input[1], virtualKeyCode, Up: true); WinAPI.SendInput(1, new INPUT[] { input[1] }, Marshal.SizeOf(typeof(INPUT))); }
private KEYBDINPUT(VK vk, ushort scan, KEYEVENTF flags) { _wVk = vk; _wScan = scan; _dwFlags = flags; _time = 0; _dwExtraInfo = IntPtr.Zero; }
/// <summary> /// send a single virtual key event /// </summary> /// <param name="key">the key to send</param> public static void SendVirtualKey(VK key) { LOG(key.ToString()); KeyDown(key); Thread.Sleep(KeyDelay); KeyUp(key); Thread.Sleep(KeyDelay); }
private unsafe void CreateInstance(IVkSurface vkSurface, string[] requestedExtensions, string[]?validationLayers, out Instance instance) { nint applicationName = Info.ApplicationName.Marshal(); nint engineName = Info.EngineName.Marshal(); ApplicationInfo applicationInfo = new ApplicationInfo { SType = StructureType.ApplicationInfo, PApplicationName = (byte *)applicationName, ApplicationVersion = Info.ApplicationVersion, PEngineName = (byte *)engineName, EngineVersion = Info.EngineVersion, ApiVersion = Info.APIVersion }; string[] requiredExtensions = VKAPI.GetRequiredExtensions(vkSurface, requestedExtensions); nint requiredExtensionsPointer = SilkMarshal.StringArrayToPtr(requiredExtensions); nint enabledLayerNames = 0x0; int enabledLayerCount = 0; InstanceCreateInfo createInfo = new InstanceCreateInfo { SType = StructureType.InstanceCreateInfo, PApplicationInfo = &applicationInfo, PpEnabledExtensionNames = (byte **)requiredExtensionsPointer, EnabledExtensionCount = (uint)requiredExtensions.Length, PpEnabledLayerNames = (byte **)null !, EnabledLayerCount = 0, PNext = (void *)null ! }; if (validationLayers is not null) { VKAPI.VerifyValidationLayerSupport(VK, validationLayers); enabledLayerNames = SilkMarshal.StringArrayToPtr(validationLayers); enabledLayerCount = validationLayers.Length; createInfo.PpEnabledLayerNames = (byte **)enabledLayerNames; createInfo.EnabledLayerCount = (uint)enabledLayerCount; } Log.Information(string.Format(FormatHelper.DEFAULT_LOGGING, nameof(VulkanInstance), "allocating instance.")); Result result = VK.CreateInstance(&createInfo, (AllocationCallbacks *)null !, out instance); if (result is not Result.Success) { throw new VulkanException(result, "Failed to create Vulkan instance."); } SilkMarshal.FreeString(applicationName); SilkMarshal.FreeString(engineName); SilkMarshal.FreeString(requiredExtensionsPointer); if (enabledLayerNames is not 0x0 && enabledLayerCount is not 0) { SilkMarshal.FreeString(enabledLayerNames); } }
void CreateCommandPool() { var info = new VkCommandPoolCreateInfo(); info.sType = CSGL.Vulkan.VkStructureType.CommandPoolCreateInfo; info.queueFamilyIndex = graphicsIndex; var result = VK.CreateCommandPool(device, ref info, alloc, out commandPool); }
void CreateSemaphores() { var info = new VkSemaphoreCreateInfo(); info.sType = CSGL.Vulkan.VkStructureType.SemaphoreCreateInfo; VK.CreateSemaphore(device, ref info, alloc, out imageAvailableSemaphore); VK.CreateSemaphore(device, ref info, alloc, out renderFinishedSemaphore); }
void RecreateSwapchain() { VK.DeviceWaitIdle(device); CreateSwapchain(); CreateImageViews(); CreateRenderPass(); CreateGraphicsPipeline(); CreateFramebuffers(); CreateCommandBuffers(); }
public static string VKCodeToUnicode(VK VKCode, byte[] KeyState) { StringBuilder sbString = new StringBuilder(); uint scanCode = MapVirtualKey((uint)VKCode, MAPVK_VK_TO_VSC); IntPtr HKL = GetKeyboardLayout(0); ToUnicodeEx((uint)VKCode, scanCode, KeyState, sbString, 5, 0, HKL); return(sbString.ToString()); }
/// <summary> /// Attempt to enumerate all dead keys available on the current keyboard /// layout and cache the results in <see cref="m_possible_dead_keys"/>. /// </summary> private static void AnalyzeKeyboardLayout() { m_possible_dead_keys = new Dictionary <string, int>(); m_possible_altgr_keys = new Dictionary <string, string>(); // Try every keyboard key followed by space to see which ones are // dead keys. This way, when later we want to know if a dead key is // currently buffered, we just call ToUnicode(VK.SPACE) and match // the result with what we found here. string[] no_altgr = new string[0x200]; byte[] state = new byte[256]; for (int i = 0; i < 0x400; ++i) { VK vk = (VK)(i & 0xff); bool has_shift = (i & 0x100) != 0; bool has_altgr = (i & 0x200) != 0; state[(int)VK.SHIFT] = (byte)(has_shift ? 0x80 : 0x00); state[(int)VK.CONTROL] = (byte)(has_altgr ? 0x80 : 0x00); state[(int)VK.MENU] = (byte)(has_altgr ? 0x80 : 0x00); // First the key we’re interested in, then the space key string str_if_normal = VkToUnicode(vk, (SC)0, state, (LLKHF)0); string str_if_dead = VkToUnicode(VK.SPACE); // If the AltGr gives us a result and it’s different from without // AltGr, we need to remember it. string str = str_if_dead != " " ? str_if_dead : str_if_normal; if (has_altgr) { if (no_altgr[i - 0x200] != "" && str != "" && no_altgr[i - 0x200] != str) { Log.Debug("VK {0} is “{1}” but “{2}” with AltGr", vk.ToString(), no_altgr[i - 0x200], str); m_possible_altgr_keys[no_altgr[i - 0x200]] = str; } } else { no_altgr[i] = str_if_dead != " " ? str_if_dead : str_if_normal; } // If the resulting string is not the space character, it means // that it was a dead key. Good! if (str_if_dead != " ") { m_possible_dead_keys[str_if_dead] = i; } } // Clean up key buffer VkToUnicode(VK.SPACE); VkToUnicode(VK.SPACE); }
public static bool IsKeyDown(VK vk) { if (GetAsyncKeyState(vk)) { last = vk; return(true); } return(false); }
/// <summary> /// Initializes new OAuthLogin instance. /// </summary> /// <param name="authSession">VKSession instance to authorize</param> /// <param name="securityScope">Security options to request for session</param> public OAuthLoginAssistant(VKSession authSession, VK.SecurityFlag securityScope) { if (authSession == null) throw new ArgumentNullException("authSession"); else if (securityScope == VK.SecurityFlag.None) throw new ArgumentException("Invalid security flags. Specify at least one."); this.AuthSession = authSession; this.SecurityScope = securityScope; OK_REDIRECT_URL = ((securityScope & VK.SecurityFlag.NoHTTPS) != 0 ? "http" : "https") + OK_REDIRECT_URL; }
public void Initialize() { logger.Info("Initializing core"); InitializeEndpoints(); httpListener.Start(); VK.Init(); logger.Success("Started serving"); tokenSource = new CancellationTokenSource(); ct = tokenSource.Token; listener = Task.Factory.StartNew(Listen, ct); }
/// <summary> /// Get input from the keyboard hook; return true if the key was handled /// and needs to be removed from the input chain. /// </summary> public static bool OnKey(WM ev, VK vk, SC sc, LLKHF flags) { // Remember when the user touched a key for the last time m_last_key_time = DateTime.Now; // Do nothing if we are disabled if (m_disabled) { return false; } int dead_key = SaveDeadKey(); bool ret = OnKeyInternal(ev, vk, sc, flags); RestoreDeadKey(dead_key); return ret; }
public static void Press(VK key) { Thread.Sleep(pause); SUIWinAPIs.keybd_event((byte)key, 0, 0, 0); }
//*************************************************************************** // USER32 - Input public static void SendKeyPress(VK key) { INPUT[] inp = new INPUT[1]; inp[0].type = Win32Const.INPUT_KEYBOARD; inp[0].ki.wScan = 0; inp[0].ki.dwFlags = 0; inp[0].ki.time = 0; inp[0].ki.wVk = (ushort)key; inp[0].ki.dwExtraInfo = Api_User32.GetMessageExtraInfo(); Win32.SendInput(inp); // And now send the key release. inp[0].ki.dwFlags = Win32Const.KEYEVENTF_KEYUP; Win32.SendInput(inp); }
static void SendKeyUp(VK k) { }
static void SendKeyStroke(VK k) { }
public static void Type(VK key, int pauserate) { Thread.Sleep(pauserate); SUIWinAPIs.keybd_event((byte)key, 0, 0, 0); SUIWinAPIs.keybd_event((byte)key, 0, 2, 0); }
private static string VkToUnicode(VK vk, SC sc, byte[] keystate, LLKHF flags) { const int buflen = 4; byte[] buf = new byte[2 * buflen]; int ret = NativeMethods.ToUnicode(vk, sc, keystate, buf, buflen, flags); if (ret > 0 && ret < buflen) { return Encoding.Unicode.GetString(buf, 0, ret * 2); } return ""; }
private static bool OnKeyInternal(WM ev, VK vk, SC sc, LLKHF flags) { CheckKeyboardLayout(); bool is_keydown = (ev == WM.KEYDOWN || ev == WM.SYSKEYDOWN); bool is_keyup = !is_keydown; bool has_shift = (NativeMethods.GetKeyState(VK.SHIFT) & 0x80) != 0; bool has_altgr = (NativeMethods.GetKeyState(VK.LCONTROL) & NativeMethods.GetKeyState(VK.RMENU) & 0x80) != 0; bool has_lrshift = (NativeMethods.GetKeyState(VK.LSHIFT) & NativeMethods.GetKeyState(VK.RSHIFT) & 0x80) != 0; bool has_capslock = NativeMethods.GetKeyState(VK.CAPITAL) != 0; // Guess what key was just pressed. If we can not find a printable // representation for the key, default to its virtual key code. Key key = new Key(vk); byte[] keystate = new byte[256]; NativeMethods.GetKeyboardState(keystate); keystate[(int)VK.SHIFT] = (byte)(has_shift ? 0x80 : 0x00); keystate[(int)VK.CONTROL] = (byte)(has_altgr ? 0x80 : 0x00); keystate[(int)VK.MENU] = (byte)(has_altgr ? 0x80 : 0x00); keystate[(int)VK.CAPITAL] = (byte)(has_capslock ? 0x01 : 0x00); string str_if_normal = KeyToUnicode(vk, sc, keystate, flags); string str_if_dead = KeyToUnicode(VK.SPACE); if (str_if_normal != "") { // This appears to be a normal, printable key key = new Key(str_if_normal); } else if (str_if_dead != " ") { // This appears to be a dead key key = new Key(str_if_dead); } // Special case: we don't consider characters such as Esc as printable // otherwise they are not properly serialised in the config file. if (key.IsPrintable() && key.ToString()[0] < ' ') { key = new Key(vk); } Log("WM.{0} {1} (VK:0x{2:X02} SC:0x{3:X02})", ev.ToString(), key.FriendlyName, (int)vk, (int)sc); // FIXME: we don’t properly support compose keys that also normally // print stuff, such as `. if (key == Settings.ComposeKey.Value) { if (is_keyup) { // If we receive a keyup for the compose key, but we hadn't // previously marked it as down, it means we're in emulation // mode and we need to cancel it. if (!m_compose_down) { Log("Fallback Off"); SendKeyUp(Settings.ComposeKey.Value.VirtualKey); } m_compose_down = false; } else if (is_keydown && !m_compose_down) { // FIXME: we don't want compose + compose to disable composing, // since there are compose sequences that use Multi_key. // FIXME: also, if a sequence was in progress, print it! m_compose_down = true; m_composing = !m_composing; if (!m_composing) m_sequence.Clear(); Log("{0} Composing", m_composing ? "Now" : "No Longer"); // Lauch the sequence reset expiration thread // FIXME: do we need to launch a new thread each time the // compose key is pressed? Let's have a dormant thread instead if (m_composing && Settings.ResetDelay.Value > 0) { new Thread(() => { while (m_composing && DateTime.Now < m_last_key_time.AddMilliseconds(Settings.ResetDelay.Value)) Thread.Sleep(50); ResetSequence(); }).Start(); } } Changed(null, new EventArgs()); return true; } // Feature: emulate capslock key with both shift keys, and optionally // disable capslock using only one shift key. if (key.VirtualKey == VK.LSHIFT || key.VirtualKey == VK.RSHIFT) { if (is_keyup && has_lrshift && Settings.EmulateCapsLock.Value) { SendKeyPress(VK.CAPITAL); return false; } if (is_keydown && has_capslock && Settings.ShiftDisablesCapsLock.Value) { SendKeyPress(VK.CAPITAL); return false; } } // If we are not currently composing a sequence, do nothing. But if // this was a dead key, eat it. if (!m_composing) { return false; } // If the compose key is down, maybe there is a key combination // going on, such as Alt+Tab or Windows+Up, so we abort composing // and tell the OS that the key is down. if (m_compose_down && (Settings.KeepOriginalKey.Value || !Settings.IsUsableKey(key))) { Log("Fallback On"); ResetSequence(); SendKeyDown(Settings.ComposeKey.Value.VirtualKey); return false; } // If the key can't be used in a sequence, just ignore it. if (!Settings.IsUsableKey(key)) { return false; } // If we reached this point, everything else ignored this key, so it // is a key we must add to the current sequence. if (is_keydown) { return AddToSequence(key); } return true; }
static bool IsPressed(VK key) { return Convert.ToBoolean(NativeMethods.GetAsyncKeyState((int)key) & KEY_PRESSED); }
private static void SendKeyPress(VK vk, KEYEVENTF flags = 0) { SendKeyDown(vk, flags); SendKeyUp(vk, flags); }
internal static extern uint MapVirtualKey(VK uCode, MAPVK uMapType);
internal static extern uint MapVirtualKeyEx(VK uCode, MAPVK uMapType, IntPtr dwhkl);
public static extern short GetKeyState(VK nVirtKey);
private static bool OnKeyInternal(WM ev, VK vk, SC sc, LLKHF flags) { //CheckKeyboardLayout(); bool is_keydown = (ev == WM.KEYDOWN || ev == WM.SYSKEYDOWN); bool is_keyup = !is_keydown; bool is_capslock_hack = false; bool has_shift = (NativeMethods.GetKeyState(VK.SHIFT) & 0x80) != 0; bool has_altgr = (NativeMethods.GetKeyState(VK.LCONTROL) & NativeMethods.GetKeyState(VK.RMENU) & 0x80) != 0; bool has_lrshift = (NativeMethods.GetKeyState(VK.LSHIFT) & NativeMethods.GetKeyState(VK.RSHIFT) & 0x80) != 0; bool has_capslock = NativeMethods.GetKeyState(VK.CAPITAL) != 0; // Guess what the system would print if we weren’t interfering. If // a printable representation exists, use that. Otherwise, default // to its virtual key code. Key key = VkToKey(vk, sc, flags, has_shift, has_altgr, has_capslock); // If Caps Lock is on, and the Caps Lock hack is enabled, we check // whether this key without Caps Lock gives a non-ASCII alphabetical // character. If so, we replace “result” with the lowercase or // uppercase variant of that character. if (has_capslock && Settings.CapsLockCapitalizes.Value) { Key alt_key = VkToKey(vk, sc, flags, has_shift, has_altgr, false); if (alt_key.IsPrintable() && alt_key.ToString()[0] > 0x7f) { string str_upper = alt_key.ToString().ToUpper(); string str_lower = alt_key.ToString().ToLower(); if (str_upper != str_lower) { key = new Key(has_shift ? str_lower : str_upper); is_capslock_hack = true; } } } // Update statistics if (is_keydown) { // Update single key statistics Stats.AddKey(key); // Update key pair statistics if applicable if (DateTime.Now < m_last_key_time.AddMilliseconds(2000) && m_last_key != null) { Stats.AddPair(m_last_key, key); } // Remember when we pressed a key for the last time m_last_key_time = DateTime.Now; m_last_key = key; } // FIXME: we don’t properly support compose keys that also normally // print stuff, such as `. if (key == Settings.ComposeKey.Value) { // If we receive a keyup for the compose key while in emulation // mode, we’re done. Send a KeyUp event and exit emulation mode. if (is_keyup && CurrentState == State.Combination) { Log.Debug("Combination Off"); CurrentState = State.Idle; m_compose_down = false; // If relevant, send an additional KeyUp for the opposite // key; experience indicates that it helps unstick some // applications such as mintty.exe. switch (Settings.ComposeKey.Value.VirtualKey) { case VK.LMENU: SendKeyUp(VK.RMENU); break; case VK.RMENU: SendKeyUp(VK.LMENU); break; case VK.LSHIFT: SendKeyUp(VK.RSHIFT); break; case VK.RSHIFT: SendKeyUp(VK.LSHIFT); break; case VK.LCONTROL: SendKeyUp(VK.RCONTROL); break; case VK.RCONTROL: SendKeyUp(VK.LCONTROL); break; } return false; } if (is_keydown && !m_compose_down) { // FIXME: we don't want compose + compose to disable composing, // since there are compose sequences that use Multi_key. switch (CurrentState) { case State.Sequence: // FIXME: also, if a sequence was in progress, print it! CurrentState = State.Idle; m_sequence.Clear(); break; case State.Idle: CurrentState = State.Sequence; // Lauch the sequence reset expiration thread // FIXME: do we need to launch a new thread each time the // compose key is pressed? Let's have a dormant thread instead if (Settings.ResetDelay.Value > 0) { new Thread(() => { while (CurrentState == State.Sequence && DateTime.Now < m_last_key_time.AddMilliseconds(Settings.ResetDelay.Value)) Thread.Sleep(50); ResetSequence(); }).Start(); } break; } Log.Debug("{0} Composing", IsComposing() ? "Now" : "No Longer"); } m_compose_down = is_keydown; return true; } // Feature: emulate capslock key with both shift keys, and optionally // disable capslock using only one shift key. if (key.VirtualKey == VK.LSHIFT || key.VirtualKey == VK.RSHIFT) { if (is_keyup && has_lrshift && Settings.EmulateCapsLock.Value) { SendKeyPress(VK.CAPITAL); return false; } if (is_keydown && has_capslock && Settings.ShiftDisablesCapsLock.Value) { SendKeyPress(VK.CAPITAL); return false; } } // If we are not currently composing a sequence, do nothing unless // one of our hacks forces us to send the key as a string (for // instance the Caps Lock capitalisation feature). if (CurrentState != State.Sequence) { if (is_capslock_hack && is_keydown) { SendString(key.ToString()); return true; } // If this was a dead key, it will be completely ignored. But // it’s okay since we stored it. return false; } // If the compose key is down and the user pressed a new key, maybe // they want to do a key combination instead of composing, such as // Alt+Tab or Windows+Up. So we abort composing and send the KeyDown // event for the Compose key that we previously discarded. // // Never do this if the event is KeyUp. // Never do this if we already started a sequence // Never do this if the key is a modifier key such as shift or alt. if (m_compose_down && is_keydown && m_sequence.Count == 0 && !key.IsModifier() && (Settings.KeepOriginalKey.Value || !key.IsUsable())) { Log.Debug("Combination On"); ResetSequence(); SendKeyDown(Settings.ComposeKey.Value.VirtualKey); CurrentState = State.Combination; return false; } // If the key can't be used in a sequence, just ignore it. if (!key.IsUsable()) { return false; } // If we reached this point, everything else ignored this key, so it // is a key we must add to the current sequence. if (is_keydown) { Log.Debug("Adding To Sequence: {0}", key.FriendlyName); return AddToSequence(key); } return true; }
void Awake() { DontDestroyOnLoad (transform.gameObject); _vk = (VK)GetComponent<VK> (); }
private static Key VkToKey(VK vk, SC sc, LLKHF flags, bool has_shift, bool has_altgr, bool has_capslock) { byte[] keystate = new byte[256]; NativeMethods.GetKeyboardState(keystate); keystate[(int)VK.SHIFT] = (byte)(has_shift ? 0x80 : 0x00); keystate[(int)VK.CONTROL] = (byte)(has_altgr ? 0x80 : 0x00); keystate[(int)VK.MENU] = (byte)(has_altgr ? 0x80 : 0x00); keystate[(int)VK.CAPITAL] = (byte)(has_capslock ? 0x01 : 0x00); // These two calls must be done together and in this order. string str_if_normal = VkToUnicode(vk, sc, keystate, flags); string str_if_dead = VkToUnicode(VK.SPACE); if (str_if_dead != " ") return new Key(str_if_dead); // Special case: we don't consider characters such as Esc as printable // otherwise they are not properly serialised in the config file. if (str_if_normal == "" || str_if_normal[0] < ' ') return new Key(vk); return new Key(str_if_normal); }
private static void SendKeyPress(VK vk) { SendKeyDown(vk); SendKeyUp(vk); }
private static bool OnKeyInternal(WM ev, VK vk, SC sc, LLKHF flags) { bool is_keydown = (ev == WM.KEYDOWN || ev == WM.SYSKEYDOWN); bool is_keyup = !is_keydown; bool add_to_sequence = is_keydown; bool is_capslock_hack = false; bool compose_is_altgr = m_possible_altgr_keys.Count > 0 && Settings.ComposeKey.Value.VirtualKey == VK.RMENU; bool has_shift = (NativeMethods.GetKeyState(VK.SHIFT) & 0x80) != 0; bool has_altgr = (NativeMethods.GetKeyState(VK.LCONTROL) & NativeMethods.GetKeyState(VK.RMENU) & 0x80) != 0; bool has_lrshift = (NativeMethods.GetKeyState(VK.LSHIFT) & NativeMethods.GetKeyState(VK.RSHIFT) & 0x80) != 0; bool has_capslock = NativeMethods.GetKeyState(VK.CAPITAL) != 0; // Guess what the system would print if we weren’t interfering. If // a printable representation exists, use that. Otherwise, default // to its virtual key code. Key key = VkToKey(vk, sc, flags, has_shift, has_altgr, has_capslock); // If Caps Lock is on, and the Caps Lock hack is enabled, we check // whether this key without Caps Lock gives a non-ASCII alphabetical // character. If so, we replace “result” with the lowercase or // uppercase variant of that character. if (has_capslock && Settings.CapsLockCapitalizes.Value) { Key alt_key = VkToKey(vk, sc, flags, has_shift, has_altgr, false); if (alt_key.IsPrintable() && alt_key.ToString()[0] > 0x7f) { string str_upper = alt_key.ToString().ToUpper(); string str_lower = alt_key.ToString().ToLower(); // Hack for German keyboards: it seems that ToUpper() does // not properly change ß into ẞ. if (str_lower == "ß") str_upper = "ẞ"; if (str_upper != str_lower) { key = new Key(has_shift ? str_lower : str_upper); is_capslock_hack = true; } } } // Update statistics if (is_keydown) { // Update single key statistics Stats.AddKey(key); // Update key pair statistics if applicable if (DateTime.Now < m_last_key_time.AddMilliseconds(2000) && m_last_key != null) { Stats.AddPair(m_last_key, key); } // Remember when we pressed a key for the last time m_last_key_time = DateTime.Now; m_last_key = key; } // If the special Synergy window has focus, we’re actually sending // keystrokes to another computer; disable WinCompose. if (m_window_is_synergy) { return false; } // If we receive a keyup for the compose key while in emulation // mode, we’re done. Send a KeyUp event and exit emulation mode. if (is_keyup && key == Settings.ComposeKey.Value && CurrentState == State.Combination) { Log.Debug("Combination Off"); CurrentState = State.Idle; m_compose_counter = 0; // If relevant, send an additional KeyUp for the opposite // key; experience indicates that it helps unstick some // applications such as mintty.exe. switch (Settings.ComposeKey.Value.VirtualKey) { case VK.LMENU: SendKeyUp(VK.RMENU); break; case VK.RMENU: SendKeyUp(VK.LMENU); if (compose_is_altgr) SendKeyUp(VK.LCONTROL); break; case VK.LSHIFT: SendKeyUp(VK.RSHIFT); break; case VK.RSHIFT: SendKeyUp(VK.LSHIFT); break; case VK.LCONTROL: SendKeyUp(VK.RCONTROL); break; case VK.RCONTROL: SendKeyUp(VK.LCONTROL); break; } return false; } // If this is the compose key and we’re idle, enter Sequence mode if (is_keydown && key == Settings.ComposeKey.Value && m_compose_counter == 0 && CurrentState == State.Idle) { Log.Debug("Now Composing"); CurrentState = State.Sequence; ++m_compose_counter; // Lauch the sequence reset expiration thread // FIXME: do we need to launch a new thread each time the // compose key is pressed? Let's have a dormant thread instead if (Settings.ResetDelay.Value > 0) { new Thread(() => { while (CurrentState == State.Sequence && DateTime.Now < m_last_key_time.AddMilliseconds(Settings.ResetDelay.Value)) Thread.Sleep(50); ResetSequence(); }).Start(); } return true; } // If this is a compose key KeyDown event and it’s already down, or it’s // a KeyUp and it’s already up, eat this event without forwarding it. if (key == Settings.ComposeKey.Value && is_keydown == ((m_compose_counter & 1) != 0)) { return true; } // Escape and backspace cancel the current sequence if (is_keydown && CurrentState == State.Sequence && (key.VirtualKey == VK.ESCAPE || key.VirtualKey == VK.BACK)) { // FIXME: if a sequence was in progress, maybe print it! Log.Debug("No Longer Composing"); ResetSequence(); return true; } // Feature: emulate capslock key with both shift keys, and optionally // disable capslock using only one shift key. if (key.VirtualKey == VK.LSHIFT || key.VirtualKey == VK.RSHIFT) { if (is_keyup && has_lrshift && Settings.EmulateCapsLock.Value) { SendKeyPress(VK.CAPITAL); return false; } if (is_keydown && has_capslock && Settings.ShiftDisablesCapsLock.Value) { SendKeyPress(VK.CAPITAL); return false; } } // If we are not currently composing a sequence, do nothing unless // one of our hacks forces us to send the key as a string (for // instance the Caps Lock capitalisation feature). if (CurrentState != State.Sequence) { if (is_capslock_hack && is_keydown) { SendString(key.ToString()); return true; } // If this was a dead key, it will be completely ignored. But // it’s okay since we stored it. Log.Debug("Forwarding Key to System (not composing)"); return false; } // If the compose key is down and the user pressed a new key, maybe // instead of composing they want to do a key combination, such as // Alt+Tab or Windows+Up. So we abort composing and send the KeyDown // event for the Compose key that we previously discarded. The same // goes for characters that need AltGr when AltGr is the compose key. // // Never do this if the event is KeyUp. // Never do this if we already started a sequence // Never do this if the key is a modifier key such as shift or alt. if (m_compose_counter == 1 && is_keydown && m_sequence.Count == 0 && !key.IsModifier()) { bool keep_original = Settings.KeepOriginalKey.Value; bool key_unusable = !key.IsUsable(); bool altgr_combination = compose_is_altgr && m_possible_altgr_keys.ContainsKey(key.ToString()); if (keep_original || key_unusable || altgr_combination) { Log.Debug("Combination On"); ResetSequence(); if (compose_is_altgr) { // It’s necessary to use KEYEVENTF_EXTENDEDKEY otherwise the system // does not understand that we’re sending AltGr. SendKeyDown(VK.LCONTROL); SendKeyDown(VK.RMENU, KEYEVENTF.EXTENDEDKEY); } else { SendKeyDown(Settings.ComposeKey.Value.VirtualKey); } CurrentState = State.Combination; return false; } } // If this is the compose key again, use our custom virtual key // FIXME: we don’t properly support compose keys that also normally // print stuff, such as `. if (key == Settings.ComposeKey.Value) { ++m_compose_counter; key = new Key(VK.COMPOSE); // If the compose key is AltGr, we only add it to the sequence // if it’s a KeyUp event, otherwise we may be adding Multi_key to the // sequence when the user actually wants to enter an AltGr char. if (compose_is_altgr && m_compose_counter > 2) add_to_sequence = is_keyup; } // If the compose key is AltGr and it’s down, check whether the current // key needs translating. if (compose_is_altgr && (m_compose_counter & 1) != 0) { string altgr_variant; if (m_possible_altgr_keys.TryGetValue(key.ToString(), out altgr_variant)) { key = new Key(altgr_variant); // Do as if we already released Compose, otherwise the next KeyUp // event will cause VK.COMPOSE to be added to the sequence… ++m_compose_counter; } } // If the key can't be used in a sequence, just ignore it. if (!key.IsUsable()) { Log.Debug("Forwarding Key to System (no possible sequence uses it)"); return false; } // If we reached this point, everything else ignored this key, so it // is a key we must add to the current sequence. if (add_to_sequence) { Log.Debug("Adding to Sequence: {0}", key.FriendlyName); return AddToSequence(key); } return true; }
private static void SendKeyDown(VK vk, KEYEVENTF flags = 0) { NativeMethods.keybd_event(vk, 0, flags, 0); }
private static string VkToUnicode(VK vk) { return VkToUnicode(vk, (SC)0, new byte[256], (LLKHF)0); }
static void SendKeyDown(VK k) { }
private static void SendString(string str) { List<VK> modifiers = new List<VK>(); /* HACK: GTK+ applications behave differently with Unicode, and some * applications such as XChat for Windows rename their own top-level * window, so we parse through the names we know in order to detect * a GTK+ application. */ bool use_gtk_hack = m_window_is_gtk; /* HACK: in MS Office, some symbol insertions change the text font * without returning to the original font. To avoid this, we output * a space character, then go left, insert our actual symbol, then * go right and backspace. */ /* These are the actual window class names for Outlook and Word… * TODO: PowerPoint ("PP(7|97|9|10)FrameClass") */ bool use_office_hack = m_window_is_office && Settings.InsertZwsp.Value; /* Clear keyboard modifiers if we need one of our custom hacks */ if (use_gtk_hack || use_office_hack) { VK[] all_modifiers = new VK[] { VK.LSHIFT, VK.RSHIFT, VK.LCONTROL, VK.RCONTROL, VK.LMENU, VK.RMENU, /* Needs to be released, too, otherwise Caps Lock + é on * a French keyboard will print garbage if Caps Lock is * not released soon enough. See note below. */ VK.CAPITAL, }; foreach (VK vk in all_modifiers) if ((NativeMethods.GetKeyState(vk) & 0x80) == 0x80) modifiers.Add(vk); foreach (VK vk in modifiers) SendKeyUp(vk); } if (use_gtk_hack) { /* XXX: We need to disable caps lock because GTK’s Shift-Ctrl-U * input mode (see below) doesn’t work when Caps Lock is on. */ bool has_capslock = NativeMethods.GetKeyState(VK.CAPITAL) != 0; if (has_capslock) SendKeyPress(VK.CAPITAL); foreach (var ch in str) { if (false) { /* FIXME: there is a possible optimisation here where we do * not have to send the whole unicode sequence for regular * ASCII characters. However, SendKeyPress() needs a VK, so * we need an ASCII to VK conversion method, together with * the proper keyboard modifiers. Maybe not worth it. * Also, we cannot use KeySequence because GTK+ seems to * ignore SendInput(). */ //SendKeyPress((VK)char.ToUpper(ch)); } else { /* Wikipedia says Ctrl+Shift+u, release, then type the four * hex digits, and press Enter. * (http://en.wikipedia.org/wiki/Unicode_input). */ SendKeyDown(VK.LCONTROL); SendKeyDown(VK.LSHIFT); SendKeyPress((VK)'U'); SendKeyUp(VK.LSHIFT); SendKeyUp(VK.LCONTROL); foreach (var key in String.Format("{0:X04} ", (short)ch)) SendKeyPress((VK)key); } } if (has_capslock) SendKeyPress(VK.CAPITAL); } else { InputSequence Seq = new InputSequence(); if (use_office_hack) { Seq.AddInput((ScanCodeShort)'\u200b'); Seq.AddInput((VirtualKeyShort)VK.LEFT); } foreach (char ch in str) { Seq.AddInput((ScanCodeShort)ch); } if (use_office_hack) { Seq.AddInput((VirtualKeyShort)VK.RIGHT); } Seq.Send(); } /* Restore keyboard modifiers if we needed one of our custom hacks */ if (use_gtk_hack || use_office_hack) { foreach (VK vk in modifiers) SendKeyDown(vk); } }
private static void SendString(string str) { List<VK> modifiers = new List<VK>(); bool use_gtk_hack = false, use_office_hack = false; const int len = 256; StringBuilder buf = new StringBuilder(len); var hwnd = NativeMethods.GetForegroundWindow(); if (NativeMethods.GetClassName(hwnd, buf, len) > 0) { string wclass = buf.ToString(); /* HACK: GTK+ applications behave differently with Unicode, and some * applications such as XChat for Windows rename their own top-level * window, so we parse through the names we know in order to detect * a GTK+ application. */ if (wclass == "gdkWindowToplevel" || wclass == "xchatWindowToplevel") use_gtk_hack = true; /* HACK: in MS Office, some symbol insertions change the text font * without returning to the original font. To avoid this, we output * a space character, then go left, insert our actual symbol, then * go right and backspace. */ /* These are the actual window class names for Outlook and Word… * TODO: PowerPoint ("PP(7|97|9|10)FrameClass") */ if (wclass == "rctrl_renwnd32" || wclass == "OpusApp") use_office_hack = true && Settings.InsertZwsp.Value; } /* Clear keyboard modifiers if we need one of our custom hacks */ if (use_gtk_hack || use_office_hack) { VK[] all_modifiers = new VK[] { VK.LSHIFT, VK.RSHIFT, VK.LCONTROL, VK.RCONTROL, VK.LMENU, VK.RMENU, }; foreach (VK vk in all_modifiers) if ((NativeMethods.GetKeyState(vk) & 0x80) == 0x80) modifiers.Add(vk); foreach (VK vk in modifiers) SendKeyUp(vk); } if (use_gtk_hack) { foreach (var ch in str) { if (false) { /* FIXME: there is a possible optimisation here where we do * not have to send the whole unicode sequence for regular * ASCII characters. However, SendKeyPress() needs a VK, so * we need an ASCII to VK conversion method, together with * the proper keyboard modifiers. Maybe not worth it. * Also, we cannot use KeySequence because GTK+ seems to * ignore SendInput(). */ //SendKeyPress((VK)char.ToUpper(ch)); } else { /* Wikipedia says Ctrl+Shift+u, release, then type the four * hex digits, and press Enter. * (http://en.wikipedia.org/wiki/Unicode_input). */ SendKeyDown(VK.LCONTROL); SendKeyDown(VK.LSHIFT); SendKeyPress((VK)'U'); SendKeyUp(VK.LSHIFT); SendKeyUp(VK.LCONTROL); foreach (var key in String.Format("{0:X04} ", (short)ch)) SendKeyPress((VK)key); } } } else { InputSequence Seq = new InputSequence(); if (use_office_hack) { Seq.AddInput((ScanCodeShort)'\u200b'); Seq.AddInput((VirtualKeyShort)VK.LEFT); } foreach (char ch in str) { Seq.AddInput((ScanCodeShort)ch); } if (use_office_hack) { Seq.AddInput((VirtualKeyShort)VK.RIGHT); } Seq.Send(); } /* Restore keyboard modifiers if we needed one of our custom hacks */ if (use_gtk_hack || use_office_hack) { foreach (VK vk in modifiers) SendKeyDown(vk); } }
private static void SendKeyUp(VK vk, KEYEVENTF flags = 0) { NativeMethods.keybd_event(vk, 0, KEYEVENTF.KEYUP | flags, 0); }
public static void Type(VK key) { Type(key, pause); }
/// <summary> /// Get input from the keyboard hook; return true if the key was handled /// and needs to be removed from the input chain. /// </summary> public static bool OnKey(WM ev, VK vk, SC sc, LLKHF flags) { // Remember when the user touched a key for the last time m_last_key_time = DateTime.Now; // Do nothing if we are disabled; NOTE: this disables stats, too if (Settings.Disabled.Value) { return false; } // We need to check the keyboard layout before we save the dead // key, otherwise we may be saving garbage. CheckKeyboardLayout(); int dead_key = SaveDeadKey(); bool ret = OnKeyInternal(ev, vk, sc, flags); RestoreDeadKey(dead_key); return ret; }
internal static bool IsExtendedKey(VK key) { /* http://msdn.microsoft.com/en-us/library/windows/desktop/ms646267(v=vs.85).aspx * The extended-key flag indicates whether the keystroke message originated from one * of the additional keys on the enhanced keyboard. The extended keys consist of the * ALT and CTRL keys on the right-hand side of the keyboard; the INS, DEL, HOME, END, * PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; * the NUM LOCK key; the BREAK (CTRL+PAUSE) key; the PRINT SCRN key; and the divide (/) * and ENTER keys in the numeric keypad. The extended-key flag is set if the key is an * extended key. */ return (key == VK.Menu || key == VK.RightMenu || key == VK.Control || key == VK.RightControl || key == VK.Insert || key == VK.Delete || key == VK.Home || key == VK.End || key == VK.Prior || key == VK.Next || key == VK.Left || key == VK.Right || key == VK.Up || key == VK.Down || key == VK.NumLock || key == VK.Cancel || key == VK.Snapshot || key == VK.Divide); }
private static void SendKeyDown(VK vk) { NativeMethods.keybd_event(vk, 0, 0, 0); }
public static void Release(VK key) { Thread.Sleep(pause); SUIWinAPIs.keybd_event((byte)key, 0, 2, 0); }