From 6d219511fc2f5ccdee5bddeab77dac5a148d6cfd Mon Sep 17 00:00:00 2001 From: Serge <5920850+seerge@users.noreply.github.com> Date: Wed, 31 May 2023 17:23:52 +0200 Subject: [PATCH] FN-Lock preparations --- app/Extra.Designer.cs | 14 +-- app/Gpu/NvidiaGpuControl.cs | 17 ++-- app/HardwareControl.cs | 34 ++++++++ app/InputDispatcher.cs | 115 +++++++++++++++++++------ app/KeyboardHook.cs | 164 ++++++++++++++++++++++++++++++++++++ app/NativeMethods.cs | 63 +------------- app/Program.cs | 2 +- app/Settings.cs | 63 +++----------- 8 files changed, 313 insertions(+), 159 deletions(-) create mode 100644 app/KeyboardHook.cs diff --git a/app/Extra.Designer.cs b/app/Extra.Designer.cs index 1ce3bdf8..32daad53 100644 --- a/app/Extra.Designer.cs +++ b/app/Extra.Designer.cs @@ -693,7 +693,7 @@ namespace GHelper groupOther.Dock = DockStyle.Top; groupOther.Location = new Point(10, 897); groupOther.Name = "groupOther"; - groupOther.Size = new Size(954, 310); + groupOther.Size = new Size(954, 319); groupOther.TabIndex = 2; groupOther.TabStop = false; groupOther.Text = "Other"; @@ -701,7 +701,7 @@ namespace GHelper // checkGpuApps // checkGpuApps.AutoSize = true; - checkGpuApps.Location = new Point(25, 220); + checkGpuApps.Location = new Point(25, 92); checkGpuApps.Name = "checkGpuApps"; checkGpuApps.Size = new Size(544, 36); checkGpuApps.TabIndex = 48; @@ -711,7 +711,7 @@ namespace GHelper // checkAutoApplyWindowsPowerMode // checkAutoApplyWindowsPowerMode.AutoSize = true; - checkAutoApplyWindowsPowerMode.Location = new Point(25, 268); + checkAutoApplyWindowsPowerMode.Location = new Point(25, 260); checkAutoApplyWindowsPowerMode.Name = "checkAutoApplyWindowsPowerMode"; checkAutoApplyWindowsPowerMode.Size = new Size(416, 36); checkAutoApplyWindowsPowerMode.TabIndex = 47; @@ -721,7 +721,7 @@ namespace GHelper // checkKeyboardAuto // checkKeyboardAuto.AutoSize = true; - checkKeyboardAuto.Location = new Point(25, 40); + checkKeyboardAuto.Location = new Point(25, 50); checkKeyboardAuto.MaximumSize = new Size(780, 0); checkKeyboardAuto.Name = "checkKeyboardAuto"; checkKeyboardAuto.Size = new Size(712, 36); @@ -732,7 +732,7 @@ namespace GHelper // checkUSBC // checkUSBC.AutoSize = true; - checkUSBC.Location = new Point(25, 85); + checkUSBC.Location = new Point(25, 134); checkUSBC.Name = "checkUSBC"; checkUSBC.Size = new Size(659, 36); checkUSBC.TabIndex = 4; @@ -742,7 +742,7 @@ namespace GHelper // checkNoOverdrive // checkNoOverdrive.AutoSize = true; - checkNoOverdrive.Location = new Point(25, 130); + checkNoOverdrive.Location = new Point(25, 176); checkNoOverdrive.Name = "checkNoOverdrive"; checkNoOverdrive.Size = new Size(307, 36); checkNoOverdrive.TabIndex = 3; @@ -752,7 +752,7 @@ namespace GHelper // checkTopmost // checkTopmost.AutoSize = true; - checkTopmost.Location = new Point(25, 175); + checkTopmost.Location = new Point(25, 218); checkTopmost.Name = "checkTopmost"; checkTopmost.Size = new Size(390, 36); checkTopmost.TabIndex = 1; diff --git a/app/Gpu/NvidiaGpuControl.cs b/app/Gpu/NvidiaGpuControl.cs index e789ca62..42db69d4 100644 --- a/app/Gpu/NvidiaGpuControl.cs +++ b/app/Gpu/NvidiaGpuControl.cs @@ -1,13 +1,9 @@ -using NvAPIWrapper; -using NvAPIWrapper.GPU; +using NvAPIWrapper.GPU; using NvAPIWrapper.Native; -using NvAPIWrapper.Native.Delegates; using NvAPIWrapper.Native.GPU; using NvAPIWrapper.Native.GPU.Structures; using NvAPIWrapper.Native.Interfaces.GPU; -using System; using System.Diagnostics; -using System.Management; using static NvAPIWrapper.Native.GPU.Structures.PerformanceStates20InfoV1; namespace GHelper.Gpu; @@ -58,7 +54,7 @@ public class NvidiaGpuControl : IGpuControl try { - Process[] processes = internalGpu.GetActiveApplications(); + Process[] processes = internalGpu.GetActiveApplications(); foreach (Process process in processes) { try @@ -98,10 +94,11 @@ public class NvidiaGpuControl : IGpuControl Logger.WriteLine($"GET GPU CLOCKS: {core}, {memory}"); return 0; - } catch (Exception ex) + } + catch (Exception ex) { Logger.WriteLine("GET GPU CLOCKS:" + ex.Message); - core = memory = 0; + core = memory = 0; return -1; } @@ -155,7 +152,7 @@ public class NvidiaGpuControl : IGpuControl //Thread.Sleep(2000); return true; } - catch (Exception ex ) + catch (Exception ex) { Logger.WriteLine(ex.ToString()); return false; @@ -195,7 +192,7 @@ public class NvidiaGpuControl : IGpuControl } catch (Exception ex) { - Logger.WriteLine("SET GPU CLOCKS: "+ex.Message); + Logger.WriteLine("SET GPU CLOCKS: " + ex.Message); return -1; } diff --git a/app/HardwareControl.cs b/app/HardwareControl.cs index 66eb3adf..d4b79cda 100644 --- a/app/HardwareControl.cs +++ b/app/HardwareControl.cs @@ -179,4 +179,38 @@ public static class HardwareControl Debug.WriteLine(ex.ToString()); } } + + + public static void KillGPUApps() + { + + List tokill = new() { "EADesktop", "RadeonSoftware", "epicgameslauncher" }; + + if (AppConfig.isConfig("kill_gpu_apps")) + { + tokill.Add("nvdisplay.container"); + tokill.Add("nvcontainer"); + tokill.Add("nvcplui"); + } + + foreach (string kill in tokill) + foreach (var process in Process.GetProcessesByName(kill)) + { + try + { + process.Kill(); + Logger.WriteLine($"Stopped: {process.ProcessName}"); + } + catch (Exception ex) + { + Logger.WriteLine($"Failed to stop: {process.ProcessName} {ex.Message}"); + } + } + + if (AppConfig.isConfig("kill_gpu_apps") && GpuControl is not null && GpuControl.IsNvidia) + { + NvidiaGpuControl nvControl = (NvidiaGpuControl)GpuControl; + nvControl.KillGPUApps(); + } + } } diff --git a/app/InputDispatcher.cs b/app/InputDispatcher.cs index a133dc24..822172be 100644 --- a/app/InputDispatcher.cs +++ b/app/InputDispatcher.cs @@ -1,10 +1,8 @@ using HidLibrary; using Microsoft.Win32; using NAudio.CoreAudioApi; -using System.Collections.Generic; using System.Diagnostics; using System.Management; -using Tools; namespace GHelper { @@ -57,34 +55,23 @@ namespace GHelper System.Timers.Timer timer = new System.Timers.Timer(1000); public bool backlight = true; - private static nint windowHandle; - public static Keys keyProfile = Keys.F5; public static Keys keyApp = Keys.F12; KeyboardListener listener; - KeyHandler m1, m2, handlerProfile, handlerApp; + KeyboardHook hook = new KeyboardHook(); - public InputDispatcher(nint handle) + public InputDispatcher() { - windowHandle = handle; - byte[] result = Program.acpi.DeviceInit(); Debug.WriteLine($"Init: {BitConverter.ToString(result)}"); Program.acpi.SubscribeToEvents(WatcherEventArrived); //Task.Run(Program.acpi.RunListener); - // CTRL + SHIFT + F5 to cycle profiles - if (AppConfig.getConfig("keybind_profile") != -1) keyProfile = (Keys)AppConfig.getConfig("keybind_profile"); - - handlerProfile = new KeyHandler(KeyHandler.SHIFT | KeyHandler.CTRL, keyProfile, windowHandle); - handlerApp = new KeyHandler(KeyHandler.SHIFT | KeyHandler.CTRL, keyApp, windowHandle); - - m1 = new KeyHandler(KeyHandler.NOMOD, Keys.VolumeDown, windowHandle); - m2 = new KeyHandler(KeyHandler.NOMOD, Keys.VolumeUp, windowHandle); + hook.KeyPressed += new EventHandler(KeyPressed); RegisterKeys(); @@ -100,7 +87,7 @@ namespace GHelper if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online) kb_timeout = AppConfig.getConfig("keyboard_ac_timeout", 0); - else + else kb_timeout = AppConfig.getConfig("keyboard_timeout", 60); if (kb_timeout == 0) return; @@ -142,20 +129,26 @@ namespace GHelper public void RegisterKeys() { + // CTRL + SHIFT + F5 to cycle profiles + if (AppConfig.getConfig("keybind_profile") != -1) keyProfile = (Keys)AppConfig.getConfig("keybind_profile"); + if (AppConfig.getConfig("keybind_app") != -1) keyApp = (Keys)AppConfig.getConfig("keybind_app"); string actionM1 = AppConfig.getConfigString("m1"); string actionM2 = AppConfig.getConfigString("m2"); - handlerProfile.Unregiser(); - m1.Unregiser(); - m2.Unregiser(); + hook.UnregisterAll(); - if (keyProfile != Keys.None) handlerProfile.Register(); - if (keyApp != Keys.None) handlerApp.Register(); + if (keyProfile != Keys.None) hook.RegisterHotKey(ModifierKeys.Shift | ModifierKeys.Control, keyProfile); + if (keyApp != Keys.None) hook.RegisterHotKey(ModifierKeys.Shift | ModifierKeys.Control, keyApp); - if (actionM1 is not null && actionM1.Length > 0) m1.Register(); + if (actionM1 is not null && actionM1.Length > 0) hook.RegisterHotKey(ModifierKeys.None, Keys.VolumeDown); + if (actionM2 is not null && actionM2.Length > 0) hook.RegisterHotKey(ModifierKeys.None, Keys.VolumeUp); - if (actionM2 is not null && actionM2.Length > 0) m2.Register(); + // FN-Lock group + + //for (Keys i = Keys.F1; i < Keys.F12; i++) hook.RegisterHotKey(ModifierKeys.None, i); + //hook.RegisterHotKey(ModifierKeys.None, Keys.VolumeMute); + //hook.RegisterHotKey(ModifierKeys.None, Keys.PrintScreen); } @@ -175,12 +168,78 @@ namespace GHelper if (intKey > 0) - NativeMethods.KeyPress(intKey); + KeyboardHook.KeyPress((Keys)intKey); else LaunchProcess(command); } + public void KeyPressed(object sender, KeyPressedEventArgs e) + { + + if (e.Modifier == ModifierKeys.None) + { + Debug.WriteLine(e.Key); + switch (e.Key) + { + case Keys.F1: + KeyboardHook.KeyPress(Keys.VolumeMute); + break; + case Keys.F2: + HandleEvent(197); + break; + case Keys.F3: + HandleEvent(196); + break; + case Keys.F4: + KeyProcess("fnf4"); + break; + case Keys.F5: + KeyProcess("fnf5"); + break; + case Keys.F6: + KeyboardHook.KeyPress(Keys.Snapshot); + break; + case Keys.F7: + HandleEvent(16); + break; + case Keys.F8: + HandleEvent(32); + break; + case Keys.F9: + break; + case Keys.F10: + HandleEvent(107); + break; + case Keys.F11: + HandleEvent(108); + break; + case Keys.F12: + break; + case Keys.VolumeDown: + KeyProcess("m1"); + break; + case Keys.VolumeUp: + KeyProcess("m2"); + break; + case Keys.VolumeMute: + KeyboardHook.KeyPress(Keys.F1); + break; + default: + break; + } + } + + if (e.Modifier == (ModifierKeys.Control | ModifierKeys.Shift)) + { + if (e.Key == keyProfile) Program.settingsForm.CyclePerformanceMode(); + if (e.Key == keyApp) Program.SettingsToggle(); + } + + + } + + public static void KeyProcess(string name = "m3") { string action = AppConfig.getConfigString(name); @@ -200,13 +259,13 @@ namespace GHelper switch (action) { case "mute": - NativeMethods.KeyPress(NativeMethods.VK_VOLUME_MUTE); + KeyboardHook.KeyPress(Keys.VolumeMute); break; case "play": - NativeMethods.KeyPress(NativeMethods.VK_MEDIA_PLAY_PAUSE); + KeyboardHook.KeyPress(Keys.MediaPlayPause); break; case "screenshot": - NativeMethods.KeyPress(NativeMethods.VK_SNAPSHOT); + KeyboardHook.KeyPress(Keys.Snapshot); break; case "screen": NativeMethods.TurnOffScreen(Program.settingsForm.Handle); diff --git a/app/KeyboardHook.cs b/app/KeyboardHook.cs new file mode 100644 index 00000000..4d97e8f9 --- /dev/null +++ b/app/KeyboardHook.cs @@ -0,0 +1,164 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; + +public sealed class KeyboardHook : IDisposable +{ + // Registers a hot key with Windows. + [DllImport("user32.dll")] + private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); + // Unregisters the hot key with Windows. + [DllImport("user32.dll")] + private static extern bool UnregisterHotKey(IntPtr hWnd, int id); + + [DllImport("user32.dll")] + private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", SetLastError = true)] + public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo); + + public const int KEYEVENTF_EXTENDEDKEY = 1; + public const int KEYEVENTF_KEYUP = 2; + + public static void KeyPress(Keys key) + { + keybd_event((byte)key, 0, KEYEVENTF_EXTENDEDKEY, IntPtr.Zero); + } + + /// + /// Represents the window that is used internally to get the messages. + /// + private class Window : NativeWindow, IDisposable + { + private static int WM_HOTKEY = 0x0312; + public static Keys? fakeKey; + + public Window() + { + // create the handle for the window. + this.CreateHandle(new CreateParams()); + } + + /// + /// Overridden to get the notifications. + /// + /// + protected override void WndProc(ref Message m) + { + base.WndProc(ref m); + + // check if we got a hot key pressed. + if (m.Msg == WM_HOTKEY) + { + // get the keys. + Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); + ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF); + + // invoke the event to notify the parent. + if (KeyPressed != null) + KeyPressed(this, new KeyPressedEventArgs(modifier, key)); + } + } + + public event EventHandler KeyPressed; + + #region IDisposable Members + + public void Dispose() + { + this.DestroyHandle(); + } + + #endregion + } + + private Window _window = new Window(); + private int _currentId; + + public KeyboardHook() + { + // register the event of the inner native window. + _window.KeyPressed += delegate (object sender, KeyPressedEventArgs args) + { + if (KeyPressed != null) + KeyPressed(this, args); + }; + } + + /// + /// Registers a hot key in the system. + /// + /// The modifiers that are associated with the hot key. + /// The key itself that is associated with the hot key. + public void RegisterHotKey(ModifierKeys modifier, Keys key) + { + // increment the counter. + _currentId = _currentId + 1; + + // register the hot key. + if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key)) + throw new InvalidOperationException("Couldn’t register the hot key."); + } + + /// + /// A hot key has been pressed. + /// + public event EventHandler KeyPressed; + + #region IDisposable Members + + public void UnregisterAll() + { + // unregister all the registered hot keys. + for (int i = _currentId; i > 0; i--) + { + UnregisterHotKey(_window.Handle, i); + } + } + + public void Dispose() + { + UnregisterAll(); + // dispose the inner native window. + _window.Dispose(); + } + + #endregion +} + +/// +/// Event Args for the event that is fired after the hot key has been pressed. +/// +public class KeyPressedEventArgs : EventArgs +{ + private ModifierKeys _modifier; + private Keys _key; + + internal KeyPressedEventArgs(ModifierKeys modifier, Keys key) + { + _modifier = modifier; + _key = key; + } + + public ModifierKeys Modifier + { + get { return _modifier; } + } + + public Keys Key + { + get { return _key; } + } +} + +/// +/// The enumeration of possible modifiers. +/// +[Flags] +public enum ModifierKeys : uint +{ + None = 0, + Alt = 1, + Control = 2, + Shift = 4, + Win = 8 +} \ No newline at end of file diff --git a/app/NativeMethods.cs b/app/NativeMethods.cs index 8845eacd..e69da088 100644 --- a/app/NativeMethods.cs +++ b/app/NativeMethods.cs @@ -1,54 +1,11 @@ -using GHelper; -using System.ComponentModel; +using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; -using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; using static Tools.ScreenInterrogatory; namespace Tools { - public class KeyHandler - { - - public const int NOMOD = 0x0000; - public const int ALT = 0x0001; - public const int CTRL = 0x0002; - public const int SHIFT = 0x0004; - public const int WIN = 0x0008; - - public const int WM_HOTKEY_MSG_ID = 0x0312; - - - [DllImport("user32.dll")] - private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk); - [DllImport("user32.dll")] - private static extern bool UnregisterHotKey(IntPtr hWnd, int id); - - private int modifier; - private int key; - private IntPtr hWnd; - private int id; - public KeyHandler(int modifier, Keys key, nint handle) - { - this.modifier = modifier; - this.key = (int)key; - this.hWnd = handle; - id = this.GetHashCode(); - } - public override int GetHashCode() - { - return modifier ^ key ^ hWnd.ToInt32(); - } - public bool Register() - { - return RegisterHotKey(hWnd, id, modifier, key); - } - public bool Unregiser() - { - return UnregisterHotKey(hWnd, id); - } - } public static class ScreenInterrogatory { @@ -459,24 +416,6 @@ public class NativeMethods public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent); - public const int KEYEVENTF_EXTENDEDKEY = 1; - public const int KEYEVENTF_KEYUP = 2; - - public const int VK_MEDIA_NEXT_TRACK = 0xB0; - public const int VK_MEDIA_PLAY_PAUSE = 0xB3; - public const int VK_MEDIA_PREV_TRACK = 0xB1; - public const int VK_VOLUME_MUTE = 0xAD; - public const int VK_SNAPSHOT = 0x2C; - - [DllImport("user32.dll", SetLastError = true)] - public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo); - - public static void KeyPress(int key = VK_MEDIA_PLAY_PAUSE) - { - keybd_event((byte)key, 0, KEYEVENTF_EXTENDEDKEY, IntPtr.Zero); - } - - [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); public const int SW_RESTORE = 9; diff --git a/app/Program.cs b/app/Program.cs index ce622060..662df6d4 100644 --- a/app/Program.cs +++ b/app/Program.cs @@ -77,7 +77,7 @@ namespace GHelper trayIcon.MouseClick += TrayIcon_MouseClick; - inputDispatcher = new InputDispatcher(ds); + inputDispatcher = new InputDispatcher(); settingsForm.InitAura(); settingsForm.InitMatrix(); diff --git a/app/Settings.cs b/app/Settings.cs index 5ff110af..fdb80792 100644 --- a/app/Settings.cs +++ b/app/Settings.cs @@ -209,26 +209,6 @@ namespace GHelper } m.Result = (IntPtr)1; break; - - case KeyHandler.WM_HOTKEY_MSG_ID: - - Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); - - switch (key) - { - case Keys.VolumeDown: - InputDispatcher.KeyProcess("m1"); - break; - case Keys.VolumeUp: - InputDispatcher.KeyProcess("m2"); - break; - default: - if (key == InputDispatcher.keyProfile) CyclePerformanceMode(); - if (key == InputDispatcher.keyApp) Program.SettingsToggle(); - break; - } - - break; } try @@ -338,7 +318,7 @@ namespace GHelper if (Program.acpi.DeviceGet(AsusACPI.GPUXG) == 1) { - KillGPUApps(); + HardwareControl.KillGPUApps(); DialogResult dialogResult = MessageBox.Show("Did you close all applications running on XG Mobile?", "Disabling XG Mobile", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { @@ -973,8 +953,8 @@ namespace GHelper labelBattery.Text = battery; }); - string trayTip = "CPU" + cpuTemp + HardwareControl.cpuFan; - if (gpuTemp.Length > 0) trayTip += "\nGPU" + gpuTemp + HardwareControl.gpuFan; + string trayTip = "CPU" + cpuTemp + " " + HardwareControl.cpuFan; + if (gpuTemp.Length > 0) trayTip += "\nGPU" + gpuTemp + " " + HardwareControl.gpuFan; if (battery.Length > 0) trayTip += "\n" + battery; Program.trayIcon.Text = trayTip; @@ -1302,10 +1282,14 @@ namespace GHelper int backlight = AppConfig.getConfig("keyboard_brightness"); - if (AppConfig.isConfig("keyboard_auto") && SystemInformation.PowerStatus.PowerLineStatus != PowerLineStatus.Online) - AsusUSB.ApplyBrightness(0); - else if (backlight >= 0) - AsusUSB.ApplyBrightness(backlight); + if (backlight > 0) + { + if (AppConfig.isConfig("keyboard_auto") && SystemInformation.PowerStatus.PowerLineStatus != PowerLineStatus.Online) + AsusUSB.ApplyBrightness(1); + else + AsusUSB.ApplyBrightness(backlight); + } + } @@ -1535,29 +1519,6 @@ namespace GHelper } - protected static void KillGPUApps() - { - string[] tokill = { "EADesktop", "RadeonSoftware", "epicgameslauncher", "nvdisplay.container", "nvcontainer", "nvcplui" }; - - foreach (string kill in tokill) - foreach (var process in Process.GetProcessesByName(kill)) - { - try - { - process.Kill(); - Logger.WriteLine($"Stopped: {process.ProcessName}"); - } catch (Exception ex) - { - Logger.WriteLine($"Failed to stop: {process.ProcessName} {ex.Message}"); - } - } - - if (AppConfig.isConfig("kill_gpu_apps") && HardwareControl.GpuControl is not null && HardwareControl.GpuControl.IsNvidia) - { - NvidiaGpuControl nvControl = (NvidiaGpuControl)HardwareControl.GpuControl; - nvControl.KillGPUApps(); - } - } public void SetGPUEco(int eco, bool hardWay = false) { @@ -1575,7 +1536,7 @@ namespace GHelper int status = 1; - if (eco == 1) KillGPUApps(); + if (eco == 1) HardwareControl.KillGPUApps(); Logger.WriteLine($"Running eco command {eco}");