Created
March 16, 2018 16:05
-
-
Save rincew1nd/8a106f4c3e54ef694e934bb4ff737512 to your computer and use it in GitHub Desktop.
Global hotkeys for c# WPF application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using System.Windows; | |
using System.Windows.Forms; | |
using System.Windows.Interop; | |
using System.Windows.Media; | |
namespace WpfApplication1 | |
{ | |
/// <summary> | |
/// Interaction logic for MainWindow.xaml | |
/// </summary> | |
public partial class MainWindow : Window | |
{ | |
const int MYACTION_HOTKEY_ID = 1; | |
public MainWindow() | |
{ | |
InitializeComponent(); | |
} | |
// DLL libraries used to manage hotkeys | |
[DllImport("user32.dll")] | |
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc); | |
[DllImport("user32.dll")] | |
public static extern bool UnregisterHotKey(IntPtr hWnd, int id); | |
private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) | |
{ | |
if (msg == 0x0312) | |
{ | |
Console.WriteLine("resr"); | |
} | |
return IntPtr.Zero; | |
} | |
[Flags] | |
public enum Modifiers | |
{ | |
NoMod = 0x0000, | |
Alt = 0x0001, | |
Ctrl = 0x0002, | |
Shift = 0x0004, | |
Win = 0x0008 | |
} | |
private void Window_Loaded(object sender, RoutedEventArgs e) | |
{ | |
var source = PresentationSource.FromVisual(this as Visual) as HwndSource; | |
if (source == null) | |
throw new Exception("Could not create hWnd source from window."); | |
source.AddHook(WndProc); | |
RegisterHotKey(new WindowInteropHelper(this).Handle, MYACTION_HOTKEY_ID, (int)Modifiers.Ctrl, (int)Keys.A); | |
RegisterHotKey(new WindowInteropHelper(this).Handle, 2, (int)Modifiers.Ctrl, (int)Keys.S); | |
RegisterHotKey(new WindowInteropHelper(this).Handle, 3, (int)Modifiers.Ctrl, (int)Keys.D); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment