Implementing a drag over window option - c#

Note:
Using Windows Forms
preferably C# .NET
Question:
Best method for implementing a drag-over-window tool, similar (or identical) to that featured in process explorer, to obtain the process ID corresponding to the selected Window

I think the easiest way is to put a control on your form that acts as a starting point; you press a mouse button there, and then you move it over the screen while the button is pressed, and pick up the process ID of whatever you are pointing at. I my example I have used a panel (called _aim).
First we set up the mouse events:
private void Panel_MouseDown(object sender, MouseEventArgs e)
{
// make all mouse events being raised in the _aim panel
// regardless of whether the mouse is within the control's
// bounds or not
_aim.Capture = true;
}
private void Panel_MouseMove(object sender, MouseEventArgs e)
{
if (_aim.Capture)
{
// get the process id only if we have mouse capture
uint processId = GetProcessIdFromPoint(
_aim.PointToScreen(e.Location)).ToString();
// do something with processId (store it for remembering the
// last processId seen, to be used as MouseUp for instance)
}
}
private void Panel_MouseUp(object sender, MouseEventArgs e)
{
if (_aim.Capture)
{
// release capture if we have it
_aim.Capture = false;
// perhaps do something more (fetch info about last seen
// process id, if we stored it during MouseMove, for instance)
}
}
The GetProcessIdFromPoint method looks like this:
private uint GetProcessIdFromPoint(Point point)
{
uint procId;
WinApi.GetWindowThreadProcessId(WinApi.WindowFromPoint(point), out procId);
return procId;
}
And finally the windows API things (from pinvoke.net):
public static class WinApi
{
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
public static implicit operator System.Drawing.Point(POINT p)
{
return new System.Drawing.Point(p.X, p.Y);
}
public static implicit operator POINT(System.Drawing.Point p)
{
return new POINT(p.X, p.Y);
}
}
[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(POINT Point);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
}

Related

How to check if user is idle on UWP? [duplicate]

This question already has answers here:
Detect if user Idle on windows universal app
(2 answers)
Closed 6 years ago.
I wanted to make a function that would timeout and navigate to the main page if the user is idle for a certain period of time. After a little research, I found that the ThreadPoolTimer should suit my needs. Testing it I decided to use a 10 sec interval.
timer =ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick,TimeSpan.FromSeconds(10));
And this is where I'm at a loss. I couldn't figure out a way to check user input on a UWP without having to individually check PointerPressed, PointerExited, etc. So I did some more digging and I found a block of code that's supposed to give you a boolean value if the user is idle or not.
public static uint GetIdleTime()
{
LASTINPUTINFO lastInPut = new LASTINPUTINFO();
lastInPut.cbSize = (uint)Marshal.SizeOf(lastInPut);
GetLastInputInfo(ref lastInPut);
return ((uint)Environment.TickCount - lastInPut.dwTime);
}
public static bool IsUserIdle()
{
uint idleTime = (uint)Environment.TickCount - GetLastInputEventTickCount();
if (idleTime > 0)
{
idleTime = (idleTime / 1000);
}
else
{
idleTime = 0;
}
//user is idle for 10 sec
bool b = (idleTime >= 10);
return b;
}
private static uint GetLastInputEventTickCount()
{
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)Marshal.SizeOf(lii);
lii.dwTime = 0;
uint p = GetLastInputInfo(ref lii) ? lii.dwTime : 0;
return p;
}
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
public static readonly int SizeOf = Marshal.SizeOf<LASTINPUTINFO>();
[MarshalAs(UnmanagedType.U4)]
public UInt32 cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime;
}
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
I then call the function in the tick function and use the conditional statement if IsUserIdle() is equal to true then navigate to the main page.
public static void Timer_Tick(object sender)
{
if (IsUserIdle() == true)
{
Frame.Navigate(typeof(MainPage));
}
}
But when I start it nothing happens, and after I set a couple breakpoints I found that IsUserIdle() never returns a true value even after 10 sec of inactivity. I am completely stuck so any help would be appreciated.
GetLastInputInfo isn't supported for Windows store apps:
Minimum supported client: Windows 2000 Professional [desktop apps only]
I'm not aware of any intrinsic UWP API to detect if the user is idle, but it's definitely possible to whip up your own mechanism for doing so.
I couldn't figure out a way to check user input on a UWP without having to individually check PointerPressed, PointerExited, etc.
What's so bad about that approach? Here's my attempt:
App.xaml.cs
public sealed partial class App : Application
{
public static new App Current => (App)Application.Current;
public event EventHandler IsIdleChanged;
private DispatcherTimer idleTimer;
private bool isIdle;
public bool IsIdle
{
get
{
return isIdle;
}
private set
{
if (isIdle != value)
{
isIdle = value;
IsIdleChanged?.Invoke(this, EventArgs.Empty);
}
}
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
idleTimer = new DispatcherTimer();
idleTimer.Interval = TimeSpan.FromSeconds(10); // 10s idle delay
idleTimer.Tick += onIdleTimerTick;
Window.Current.CoreWindow.PointerMoved += onCoreWindowPointerMoved;
}
private void onIdleTimerTick(object sender, object e)
{
idleTimer.Stop();
IsIdle = true;
}
private void onCoreWindowPointerMoved(CoreWindow sender, PointerEventArgs args)
{
idleTimer.Stop();
idleTimer.Start();
IsIdle = false;
}
}
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
App.Current.IsIdleChanged += onIsIdleChanged;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
App.Current.IsIdleChanged -= onIsIdleChanged;
}
private void onIsIdleChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine($"IsIdle: {App.Current.IsIdle}");
}
}
Idle is detected when the pointer hasn't moved for 10s within the app window. This will work also for touch-only apps (like mobile apps) because PointerMoved will fire when the window is tapped, too.

Restore maximzed state on secondary monitor

I have a problem about restore state of window when I maximized it on secondary monitor.
I maximized window on the not primary screen and then close.
When reopen window, it also maximized, but it is maximized on primary screen.
I want is maximized on the not primary screen (the screen display window when close).
Please help me if you know.
Note: if state of window is normal, window will be restored correct screen.
My code as below:
if (ShellState == WindowState.Maximized)
{
ShellState = WindowState.Normal;
LeftPosition = Screen.AllScreens[selectedScreen].WorkingArea.Left;
TopPosition = Screen.AllScreens[selectedScreen].WorkingArea.Top;
ShellHeight = Screen.AllScreens[selectedScreen].WorkingArea.Height;
ShellWidth = Screen.AllScreens[selectedScreen].WorkingArea.Width;
ShellState = WindowState.Maximized;
}
We had many problems on multi-screen systems using the standard WPF tools for storing and restoring the window state and size, as long as the screen assignment.
We endet with creating a custom behavior that uses the native WinAPI functions.
Here is the (simplified) source code of our behavior. You can use it in your application instead of the WPF tools.
You have to change the way the window placement will be stored. This can be a dependency property providing a container, a static Properties.Settings reference or something else. In the code below, a static ApplicationSettings reference is used as an example.
class WindowPlacementPersistenceBehavior : Behavior<Window>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SourceInitialized += this.AssociatedObject_SourceInitialized;
this.AssociatedObject.Closing += this.AssociatedObject_Closing;
}
protected override void OnDetaching()
{
this.AssociatedObject.SourceInitialized -= this.AssociatedObject_SourceInitialized;
this.AssociatedObject.Closing -= this.AssociatedObject_Closing;
base.OnDetaching();
}
private void AssociatedObject_Closing(object sender, CancelEventArgs e)
{
WINDOWPLACEMENT wp;
NativeMethods.GetWindowPlacement(new WindowInteropHelper(this.AssociatedObject).Handle, out wp);
// Here you can store the window placement
ApplicationSettings.WindowPlacement = wp.ToString();
}
private void AssociatedObject_SourceInitialized(object sender, EventArgs e)
{
// Here you can load the window placement
WINDOWPLACEMENT wp = WINDOWPLACEMENT.Parse(ApplicationSettings.WindowPlacement);
if (wp.ShowCmd == NativeMethods.SW_SHOWMINIMIZED)
{
// Don't start in the minimized state
wp.ShowCmd = NativeMethods.SW_SHOWNORMAL;
}
try
{
NativeMethods.SetWindowPlacement(new WindowInteropHelper(this.AssociatedObject).Handle, ref wp);
}
catch
{
}
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public static RECT Parse(string input)
{
RECT result;
string[] items = input.Split(';');
result.Left = int.Parse(items[0]);
result.Top = int.Parse(items[1]);
result.Right = int.Parse(items[2]);
result.Bottom = int.Parse(items[3]);
return result;
}
public override string ToString()
{
return this.Left + ";" + this.Top + ";" + this.Right + ";" + this.Bottom;
}
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int X;
public int Y;
public static POINT Parse(string input)
{
POINT result;
string[] items = input.Split(';');
result.X = int.Parse(items[0]);
result.Y = int.Parse(items[1]);
return result;
}
public override string ToString()
{
return this.X + ";" + this.Y;
}
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
private struct WINDOWPLACEMENT
{
public int Length;
public int Flags;
public int ShowCmd;
public POINT MinPosition;
public POINT MaxPosition;
public RECT NormalPosition;
public static WINDOWPLACEMENT Parse(string input)
{
WINDOWPLACEMENT result = default(WINDOWPLACEMENT);
result.Length = Marshal.SizeOf(typeof(WINDOWPLACEMENT));
try
{
string[] items = input.Split('/');
result.Flags = int.Parse(items[0]);
result.ShowCmd = int.Parse(items[1]);
result.MinPosition = POINT.Parse(items[2]);
result.MaxPosition = POINT.Parse(items[3]);
result.NormalPosition = RECT.Parse(items[4]);
}
catch
{
}
return result;
}
public override string ToString()
{
return this.Flags + "/" + this.ShowCmd + "/" + this.MinPosition.ToString() + "/" + this.MaxPosition.ToString() + "/" + this.NormalPosition.ToString();
}
}
private static class NativeMethods
{
public const int SW_SHOWNORMAL = 1;
public const int SW_SHOWMINIMIZED = 2;
[DllImport("user32.dll")]
public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll")]
public static extern bool GetWindowPlacement(IntPtr hWnd, [Out] out WINDOWPLACEMENT lpwndpl);
}
}
To use this behavior, just add it to your window in XAML:
<Window
xmlns:v="clr-namespace:YourNameSpace"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
<i:Interaction.Behaviors>
<v:WindowPlacementPersistenceBehavior />
</i:Interaction.Behaviors>
</Window>

How to create a universal keyboard shortcut?

I have searched online for this, but can't find nothing at all.
What I would like to do is to create a keyboard shortcut that I would be able to use in all applications. A universal keyboard shortcut, so that when I press, say Ctrl+Shift+X in any application, it would execute a piece of code I created in C#. For example, when I'm in Skype, I would select text and press Ctrl+Shift+X (or whatever other key combination), it would change the color of the text from black to blue. That is just an example to try and explain what I want to do. I'm thinking I would have to import a DLL and edit that (maybe user32.dll?) I'm just guessing. I have no clue how to do this, so any help will be greatly appreciated!
Thanks a lot in advance :)
PS: I am using Windows Forms Application, .NET Framework 4.0. Unclear about something I am trying to do/say? Please feel free to comment and I will get back to you right away.
Win32 has a RegisterHotKey function as part of the Win32 API. To use it in managed code (C#), you'd have to pInvoke it. Here is an example:
public class WindowsShell
{
#region fields
public static int MOD_ALT = 0x1;
public static int MOD_CONTROL = 0x2;
public static int MOD_SHIFT = 0x4;
public static int MOD_WIN = 0x8;
public static int WM_HOTKEY = 0x312;
#endregion
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private static int keyId;
public static void RegisterHotKey(Form f, Keys key)
{
int modifiers = 0;
if ((key & Keys.Alt) == Keys.Alt)
modifiers = modifiers | WindowsShell.MOD_ALT;
if ((key & Keys.Control) == Keys.Control)
modifiers = modifiers | WindowsShell.MOD_CONTROL;
if ((key & Keys.Shift) == Keys.Shift)
modifiers = modifiers | WindowsShell.MOD_SHIFT;
Keys k = key & ~Keys.Control & ~Keys.Shift & ~Keys.Alt;
keyId = f.GetHashCode(); // this should be a key unique ID, modify this if you want more than one hotkey
RegisterHotKey((IntPtr)f.Handle, keyId, (uint)modifiers, (uint)k);
}
private delegate void Func();
public static void UnregisterHotKey(Form f)
{
try
{
UnregisterHotKey(f.Handle, keyId); // modify this if you want more than one hotkey
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
public partial class Form1 : Form, IDisposable
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Keys k = Keys.A | Keys.Control;
WindowsShell.RegisterHotKey(this, k);
}
// CF Note: The WndProc is not present in the Compact Framework (as of vers. 3.5)! please derive from the MessageWindow class in order to handle WM_HOTKEY
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WindowsShell.WM_HOTKEY)
this.Visible = !this.Visible;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
WindowsShell.UnregisterHotKey(this);
}
}
This code came from this article. Read that article for more information and more examples.

Mouse wheel event to work with hovered control

In my C# 3.5 Windows Forms application, I have a few SplitContainers. There is a list control inside each (dock fill). When the focus is on one of these controls and I move mouse wheel, the list, which is now focused, is scrolled.
My task is to scroll the list, which is currently hovered by mouse, not the one which is selected. Is it possible in Windows Forms? If not, is it possible with PInvoke?
It looks like you can use the IMessageFilter and PInvoke to handle this. An example in VB can be found at Redirect Mouse Wheel Events to Unfocused Windows Forms Controls. You should be able to easily convert this to C#.
Points of Interest
This class uses the following techniques for the given task:
Listen to the control's MouseEnter and MouseLeave events to determine when the mouse pointer is over the control.
Implement IMessageFilter to catch WM_MOUSEWHEEL messages in the application.
PInvoke the Windows API call SendMessage redirecting the WM_MOUSEWHEEL message to the control's handle.
The IMessageFilter object is implemented as a singleton of the MouseWheelRedirector class and accessed by the shared members Attach, Detach, and Active.
Using a VB.NET to C# converter, this is what you end up with:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class MouseWheelRedirector : IMessageFilter
{
private static MouseWheelRedirector instance = null;
private static bool _active = false;
public static bool Active
{
get { return _active; }
set
{
if (_active != value)
{
_active = value;
if (_active)
{
if (instance == null)
{
instance = new MouseWheelRedirector();
}
Application.AddMessageFilter(instance);
}
else
{
if (instance != null)
{
Application.RemoveMessageFilter(instance);
}
}
}
}
}
public static void Attach(Control control)
{
if (!_active)
Active = true;
control.MouseEnter += instance.ControlMouseEnter;
control.MouseLeave += instance.ControlMouseLeaveOrDisposed;
control.Disposed += instance.ControlMouseLeaveOrDisposed;
}
public static void Detach(Control control)
{
if (instance == null)
return;
control.MouseEnter -= instance.ControlMouseEnter;
control.MouseLeave -= instance.ControlMouseLeaveOrDisposed;
control.Disposed -= instance.ControlMouseLeaveOrDisposed;
if (object.ReferenceEquals(instance.currentControl, control))
instance.currentControl = null;
}
private MouseWheelRedirector()
{
}
private Control currentControl;
private void ControlMouseEnter(object sender, System.EventArgs e)
{
var control = (Control)sender;
if (!control.Focused)
{
currentControl = control;
}
else
{
currentControl = null;
}
}
private void ControlMouseLeaveOrDisposed(object sender, System.EventArgs e)
{
if (object.ReferenceEquals(currentControl, sender))
{
currentControl = null;
}
}
private const int WM_MOUSEWHEEL = 0x20a;
public bool PreFilterMessage(ref System.Windows.Forms.Message m)
{
if (currentControl != null && m.Msg == WM_MOUSEWHEEL)
{
SendMessage(currentControl.Handle, m.Msg, m.WParam, m.LParam);
return true;
}
else
{
return false;
}
}
[DllImport("user32.dll", SetLastError = false)]
private static extern IntPtr SendMessage(
IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
}
I had similar question and found this thread... so posting my belated answer for others who might find this thread. In my case, I just want the mouse wheel events to go to whatever control is under the cursor... just like right-click does (it would be bewildering if right-click went to the focus control rather than the control under the cursor... I argue the same is true for the mouse wheel, except we've gotten used to it).
Anyway, the answer is super easy. Just add a PreFilterMessage to your application and have it redirect mouse wheel events to the control under the mouse:
public bool PreFilterMessage(ref Message m)
{
switch (m.Msg)
{
case WM_MOUSEWHEEL: // 0x020A
case WM_MOUSEHWHEEL: // 0x020E
IntPtr hControlUnderMouse = WindowFromPoint(new Point((int)m.LParam));
if (hControlUnderMouse == m.HWnd)
return false; // already headed for the right control
else
{
// redirect the message to the control under the mouse
SendMessage(hControlUnderMouse, m.Msg, m.WParam, m.LParam);
return true;
}
default:
return false;
}
}
This is Brian Kennedy's answer completed with Hank Schultz comment:
First you should make a class implements IMessageFilter:
public class MessageFilter : IMessageFilter
{
private const int WM_MOUSEWHEEL = 0x020A;
private const int WM_MOUSEHWHEEL = 0x020E;
[DllImport("user32.dll")]
static extern IntPtr WindowFromPoint(Point p);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
public bool PreFilterMessage(ref Message m)
{
switch (m.Msg)
{
case WM_MOUSEWHEEL:
case WM_MOUSEHWHEEL:
IntPtr hControlUnderMouse = WindowFromPoint(new Point((int)m.LParam));
if (hControlUnderMouse == m.HWnd)
{
//Do nothing because it's already headed for the right control
return false;
}
else
{
//Send the scroll message to the control under the mouse
uint u = Convert.ToUInt32(m.Msg);
SendMessage(hControlUnderMouse, u, m.WParam, m.LParam);
return true;
}
default:
return false;
}
}
}
Example usage:
public partial class MyForm : Form
{
MessageFilter mf = null;
public MyForm
{
Load += MyForm_Load;
FormClosing += MyForm_FormClosing;
}
private void MyForm_Load(object sender, EventArgs e)
{
mf= new MessageFilter();
Application.AddMessageFilter(mf);
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Application.RemoveMessageFilter(mf);
}
}
Use Control.MouseEnter Event to set focus to to the control. E.g. using ActiveControl Property

How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?

I'm building an application in C# using WPF. How can I bind to some keys?
Also, how can I bind to the Windows key?
This is a full working solution, hope it helps...
Usage:
_hotKey = new HotKey(Key.F9, KeyModifier.Shift | KeyModifier.Win, OnHotKeyHandler);
...
private void OnHotKeyHandler(HotKey hotKey)
{
SystemHelper.SetScreenSaverRunning();
}
Class:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Mime;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
namespace UnManaged
{
public class HotKey : IDisposable
{
private static Dictionary<int, HotKey> _dictHotKeyToCalBackProc;
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, UInt32 fsModifiers, UInt32 vlc);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
public const int WmHotKey = 0x0312;
private bool _disposed = false;
public Key Key { get; private set; }
public KeyModifier KeyModifiers { get; private set; }
public Action<HotKey> Action { get; private set; }
public int Id { get; set; }
// ******************************************************************
public HotKey(Key k, KeyModifier keyModifiers, Action<HotKey> action, bool register = true)
{
Key = k;
KeyModifiers = keyModifiers;
Action = action;
if (register)
{
Register();
}
}
// ******************************************************************
public bool Register()
{
int virtualKeyCode = KeyInterop.VirtualKeyFromKey(Key);
Id = virtualKeyCode + ((int)KeyModifiers * 0x10000);
bool result = RegisterHotKey(IntPtr.Zero, Id, (UInt32)KeyModifiers, (UInt32)virtualKeyCode);
if (_dictHotKeyToCalBackProc == null)
{
_dictHotKeyToCalBackProc = new Dictionary<int, HotKey>();
ComponentDispatcher.ThreadFilterMessage += new ThreadMessageEventHandler(ComponentDispatcherThreadFilterMessage);
}
_dictHotKeyToCalBackProc.Add(Id, this);
Debug.Print(result.ToString() + ", " + Id + ", " + virtualKeyCode);
return result;
}
// ******************************************************************
public void Unregister()
{
HotKey hotKey;
if (_dictHotKeyToCalBackProc.TryGetValue(Id, out hotKey))
{
UnregisterHotKey(IntPtr.Zero, Id);
}
}
// ******************************************************************
private static void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled)
{
if (!handled)
{
if (msg.message == WmHotKey)
{
HotKey hotKey;
if (_dictHotKeyToCalBackProc.TryGetValue((int)msg.wParam, out hotKey))
{
if (hotKey.Action != null)
{
hotKey.Action.Invoke(hotKey);
}
handled = true;
}
}
}
}
// ******************************************************************
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// ******************************************************************
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be _disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be _disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this._disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
Unregister();
}
// Note disposing has been done.
_disposed = true;
}
}
}
// ******************************************************************
[Flags]
public enum KeyModifier
{
None = 0x0000,
Alt = 0x0001,
Ctrl = 0x0002,
NoRepeat = 0x4000,
Shift = 0x0004,
Win = 0x0008
}
// ******************************************************************
}
I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, Save All that can be triggered from anywhere by Ctrl + Shift + S.)
You find the global UIElement of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree.
Now, first you need
to bind the Key-Combo with a Command using an InputBinding like this
you can then hookup the command to your handler (e.g. code that gets called by SaveAll) via a CommandBinding.
For the Windows Key, you use the right Key enumerated member, Key.LWin or Key.RWin
public WindowMain()
{
InitializeComponent();
// Bind Key
var ib = new InputBinding(
MyAppCommands.SaveAll,
new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control));
this.InputBindings.Add(ib);
// Bind handler
var cb = new CommandBinding( MyAppCommands.SaveAll);
cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing );
this.CommandBindings.Add (cb );
}
private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e)
{
// Do the Save All thing here.
}
Registering OS level shortcuts is hardly ever a good thing: users don't want you to mess with their OS.
That said, there is a much simpler and user friendly way of doing this in WPF, if you're ok with the hotkey working within the application only (i.e as long as your WPF app has the focus):
In App.xaml.cs :
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(Window), Window.PreviewKeyUpEvent, new KeyEventHandler(OnWindowKeyUp));
}
private void OnWindowKeyUp(object source, KeyEventArgs e))
{
//Do whatever you like with e.Key and Keyboard.Modifiers
}
It's that simple
If you're going to mix Win32 and WPF, here's how I did it:
using System;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Media;
using System.Threading;
using System.Windows;
using System.Windows.Input;
namespace GlobalKeyboardHook
{
public class KeyboardHandler : IDisposable
{
public const int WM_HOTKEY = 0x0312;
public const int VIRTUALKEYCODE_FOR_CAPS_LOCK = 0x14;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private readonly Window _mainWindow;
WindowInteropHelper _host;
public KeyboardHandler(Window mainWindow)
{
_mainWindow = mainWindow;
_host = new WindowInteropHelper(_mainWindow);
SetupHotKey(_host.Handle);
ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;
}
void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
{
if (msg.message == WM_HOTKEY)
{
//Handle hot key kere
}
}
private void SetupHotKey(IntPtr handle)
{
RegisterHotKey(handle, GetType().GetHashCode(), 0, VIRTUALKEYCODE_FOR_CAPS_LOCK);
}
public void Dispose()
{
UnregisterHotKey(_host.Handle, GetType().GetHashCode());
}
}
}
You can get the virtual-key code for the hotkey you want to register here: http://msdn.microsoft.com/en-us/library/ms927178.aspx
There may be a better way, but this is what I've got so far.
Cheers!
This is similar to the answers already given, but I find it a bit cleaner:
using System;
using System.Windows.Forms;
namespace GlobalHotkeyExampleForm
{
public partial class ExampleForm : Form
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
enum KeyModifier
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
WinKey = 8
}
public ExampleForm()
{
InitializeComponent();
int id = 0; // The id of the hotkey.
RegisterHotKey(this.Handle, id, (int)KeyModifier.Shift, Keys.A.GetHashCode()); // Register Shift + A as global hotkey.
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0312)
{
/* Note that the three lines below are not needed if you only want to register one hotkey.
* The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); // The key of the hotkey that was pressed.
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF); // The modifier of the hotkey that was pressed.
int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed.
MessageBox.Show("Hotkey has been pressed!");
// do something
}
}
private void ExampleForm_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, 0); // Unregister hotkey with id 0 before closing the form. You might want to call this more than once with different id values if you are planning to register more than one hotkey.
}
}
}
I've found it on fluxbytes.com.
With the NHotKey package, you can make your hotkey global:
https://github.com/thomaslevesque/NHotkey
https://thomaslevesque.com/2014/02/05/wpf-declare-global-hotkeys-in-xaml-with-nhotkey/ (use web.archive.org if the link is broken)
In short, for XAML, all you need to do is to replace
<KeyBinding Gesture="Ctrl+Alt+Add" Command="{Binding IncrementCommand}" />
by
<KeyBinding Gesture="Ctrl+Alt+Add" Command="{Binding IncrementCommand}"
HotkeyManager.RegisterGlobalHotkey="True" />
I'm not sure about WPF, but this may help. I used the solution described in RegisterHotKey (user32) (modified to my needs of course) for a C# Windows Forms application to assign a CTRL-KEY combination within Windows to bring up a C# form, and it worked beautifully (even on Windows Vista). I hope it helps and good luck!
I've found the Global Hotkeys in WPF project on codeproject.com which does the job for me. It's relatively recent, does not need a reference to System.Windows.Forms and works "globally" in terms of reacting to the hotkey being pressed even if "your" application is not the active window.
Baboon's solution works best because you may have multiple windows. I did tweak it so it uses the PreviewKeyDownEvent instead of the PreviewKeyUpEvent in order to handle repetition in keystrokes.
I would advise against OS-level registration unless you are writing something like a snipping tool or an audio recording app as it will let you access functionality when the window is not focused.
Although RegisterHotKey is sometimes precisely what you want, in most cases you probably do not want to use system-wide hotkeys. I ended up using code like the following:
using System.Windows;
using System.Windows.Interop;
namespace WpfApp
{
public partial class MainWindow : Window
{
const int WM_KEYUP = 0x0101;
const int VK_RETURN = 0x0D;
const int VK_LEFT = 0x25;
public MainWindow()
{
this.InitializeComponent();
ComponentDispatcher.ThreadPreprocessMessage +=
ComponentDispatcher_ThreadPreprocessMessage;
}
void ComponentDispatcher_ThreadPreprocessMessage(
ref MSG msg, ref bool handled)
{
if (msg.message == WM_KEYUP)
{
if ((int)msg.wParam == VK_RETURN)
MessageBox.Show("RETURN was pressed");
if ((int)msg.wParam == VK_LEFT)
MessageBox.Show("LEFT was pressed");
}
}
}
}
RegisterHotKey() suggested by John could work - the only catch is that it requires an HWND (using PresentationSource.FromVisual(), and casting the result to an HwndSource).
However, you'll also need to respond to the WM_HOTKEY message - I'm not sure if there is a way to get access to the WndProc of a WPF window or not (which can be done for Windows Forms windows).

Categories