Hi,
Welcome to our Microsoft Q&A platform.
Do you want uesrcontrol to respond to keyboard event when it is focused?You can remove hook ,see my example:
public partial class MainWindow : Window
{
Dictionary<string, short> hotKeyDic = new Dictionary<string, short>();
HwndSource hWndSource;
public MainWindow()
{
InitializeComponent();
this.Loaded += (sender, e) =>
{
var wpfHwnd = new WindowInteropHelper(this).Handle;
hWndSource = HwndSource.FromHwnd(wpfHwnd);
if (hWndSource != null) hWndSource.AddHook(MainWindowProc);
hotKeyDic.Add("Alt-S", Win32.GlobalAddAtom("Alt-S"));
hotKeyDic.Add("Alt-D", Win32.GlobalAddAtom("Alt-D"));
Win32.RegisterHotKey(wpfHwnd, hotKeyDic["Alt-S"], Win32.KeyModifiers.Alt, (int)System.Windows.Forms.Keys.S);
Win32.RegisterHotKey(wpfHwnd, hotKeyDic["Alt-D"], Win32.KeyModifiers.Alt, (int)System.Windows.Forms.Keys.D);
};
}
private IntPtr MainWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case Win32.WmHotkey:
{
int sid = wParam.ToInt32();
if (sid == hotKeyDic["Alt-S"])
{
MessageBox.Show("按下Alt+S");
}
else if (sid == hotKeyDic["Alt-D"])
{
MessageBox.Show("按下Alt+D");
}
handled = true;
break;
}
}
return IntPtr.Zero;
}
private void MyUserControl_GotFocus(object sender, RoutedEventArgs e)
{
hWndSource.RemoveHook(MainWindowProc);
}
private void MyUserControl_LostFocus(object sender, RoutedEventArgs e)
{
hWndSource.AddHook(MainWindowProc);
}
}
public class Win32
{
[DllImport("User32.Dll")]
public static extern void SetWindowText(int h, String s);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd,
int id,
KeyModifiers fsModifiers,
int vk
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd,
int id
);
[DllImport("kernel32", SetLastError = true)]
public static extern short GlobalAddAtom(string lpString);
[DllImport("kernel32", SetLastError = true)]
public static extern short GlobalDeleteAtom(short nAtom);
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Ctrl = 2,
Shift = 4,
WindowsKey = 8
}
public const int WmHotkey = 0x312;
}
public class MyUserControl : UserControl
{
}
xaml:
<local:MyUserControl Focusable="True" GotFocus="MyUserControl_GotFocus" LostFocus="MyUserControl_LostFocus"/>
Thanks.