WPF - 在Action中显示窗口

时间:2017-03-01 18:53:54

标签: wpf

我有一个小问题。我有注册全局热键的方法,当我按热键时,程序调用Action。在Action方法中,我想要显示窗口,但不要工作。 这是我的代码:

MainWindow.cs:

_hotKeyRegistrator.Add(Modifier.Ctrl, Keys.A, () => {Show();}

HotkeyRegistrator.cs:

public class HotkeyRegistrator
{
    private HwndSource _source;
    private readonly WindowInteropHelper _windowInteropHelper;
    private const int HotkeyId = 9000;
    private const int WmHotkey = 0x0312;
    private List<HotKey> _hotKeys;

    public HotkeyRegistrator(Window window)
    {
        _windowInteropHelper = new WindowInteropHelper(window);
        _source = HwndSource.FromHwnd(_windowInteropHelper.Handle);
        _source?.AddHook(HwndHook);
        _hotKeys = new List<HotKey>();
    }

    [DllImport("User32.dll")]
    private static extern bool RegisterHotKey([In] IntPtr hWnd, [In] int id, [In] uint fsModifiers, [In] uint vk);

    [DllImport("User32.dll")]
    private static extern bool UnregisterHotKey([In] IntPtr hWnd, [In] int id);


    public void Add(Modifiers modifier, Keys key, Action action)
        => _hotKeys.Add(new HotKey(HotkeyId + _hotKeys.Count, modifier, key, action));

    public void Register()
    {
        foreach (var hotKey in _hotKeys)
        {
            if (!RegisterHotKey(_windowInteropHelper.Handle, hotKey.Id, hotKey.Modifier, hotKey.Key))
            {
                throw new Exception("Cannot register hotkey");
            }
        }
    }

    public void UnRegisterAll()
    {
        _source.RemoveHook(HwndHook);
        _source = null;
        foreach (var hotKey in _hotKeys)
        {
            UnregisterHotKey(_windowInteropHelper.Handle, hotKey.Id);
        }
        _hotKeys = null;
    }

    private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WmHotkey)
            _hotKeys.FirstOrDefault(x => x.Id == wParam.ToInt32())?.Action.Invoke();
        return IntPtr.Zero;
    }
}

Hotkey.cs:

public class HotKey
{

    public int Id { get; set; }
    public uint Modifier { get; }
    public uint Key { get; }
    public Action Action { get; }

    public HotKey(int id, Modifiers modifier, Keys key, Action action)
    {
        Id = id;
        Modifier = (uint)modifier;
        Key = (uint)key;
        Action = action;
    }
}

使用Invoke方法调用Action方法。当我按下CTRL + A时,调用action和Show方法,但是窗口不会打开。

感谢您的建议。

1 个答案:

答案 0 :(得分:0)

问题解决了。我的窗口在启动时设置了WindowState="Minimized"属性。当我想按全局快捷键后调用Show()时,代码必须是:

_hotKeyRegistrator.Add(Modifier.Ctrl, Keys.A, () => {
    WindowState = WindowState.Normal;
    Show();
});