49

WPFを使用してC#でアプリケーションを構築しています。どうすればいくつかのキーにバインドできますか?

また、どうすればWindowsキーにバインドできますか?

4

11 に答える 11

67

これは完全に機能するソリューションです。お役に立てば幸いです...

使用法:

_hotKey = new HotKey(Key.F9, KeyModifier.Shift | KeyModifier.Win, OnHotKeyHandler);

...

private void OnHotKeyHandler(HotKey hotKey)
{
    SystemHelper.SetScreenSaverRunning();
}

クラス:

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
    }

    // ******************************************************************
}
于 2012-02-17T14:53:34.393 に答える
29

ここで「グローバル」とはどういう意味かわかりませんが、ここで説明します(たとえば、どこからでも+ +でトリガーできる、アプリケーションレベルのコマンドを意味していると仮定CtrlShiftます)S

UIElementたとえば、このバインディングが必要なすべてのコントロールの親であるトップレベルウィンドウなど、選択したグローバルが見つかります。WPFイベントの「バブリング」により、子要素でのイベントは、コントロールツリーのルートまでバブリングします。

さて、最初に必要なのは

  1. InputBindingこのようなコマンドを使用してキーコンボをコマンドにバインドするには
  2. SaveAll次に、を介してコマンドをハンドラー(たとえば、によって呼び出されるコード)に接続できますCommandBinding

キーにはWindows、適切なキー列挙メンバーを使用するか、Key.LWinまたは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.
}
于 2008-09-08T04:36:33.417 に答える
18

OS レベルのショートカットを登録することは、決して良いことではありません。ユーザーは、OS をいじってほしくないからです。

そうは言っても、ホットキーがアプリケーション内でのみ機能することに問題がない場合 (つまり、WPF アプリにフォーカスがある限り)、WPF でこれを行うためのはるかにシンプルでユーザー フレンドリーな方法があります。

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
}

それはとても簡単です

于 2012-10-01T16:05:02.727 に答える
17

Win32 と WPF を混在させる場合は、次のようにしました。

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());
        }
    }
}

登録するホットキーの仮想キー コードは、http: //msdn.microsoft.com/en-us/library/ms927178.aspxで入手できます。

もっと良い方法があるかもしれませんが、これは私が今のところ持っているものです。

乾杯!

于 2009-12-25T00:05:23.337 に答える
2

これはすでに与えられた答えに似ていますが、少しきれいだと思います:

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.
        }
    }
}

Fluxbytes.comで見つけました。

于 2015-11-19T07:10:04.563 に答える
1

WPFについてはよくわかりませんが、これが役立つ場合があります。私はRegisterHotKey(user32) (もちろん私のニーズに合わせて変更)で説明されているソリューションをC#Windowsフォームアプリケーションに使用して、Windows内でCTRL-KEYの組み合わせを割り当ててC#フォームを表示しましたが、それは(Windows Vistaでも)美しく機能しました。お役に立てば幸いです。

于 2008-09-08T00:48:13.857 に答える
1

複数のウィンドウがある可能性があるため、ヒヒのソリューションが最適です。キーストロークの繰り返しを処理するために、PreviewKeyUpEvent の代わりに PreviewKeyDownEvent を使用するように微調整しました。

ウィンドウがフォーカスされていないときに機能にアクセスできるようにするため、切り取りツールやオーディオ録音アプリなどを作成している場合を除き、OS レベルの登録はお勧めしません。

于 2013-03-26T19:42:11.873 に答える
1

私のために仕事をする codeproject.comの WPF プロジェクトのグローバル ホットキーを見つけました。これは比較的最近のもので、System.Windows.Forms への参照を必要とせず、「あなたの」アプリケーションがアクティブなウィンドウでなくても、押されたホットキーに反応するという点で「グローバル」に機能します。

于 2012-06-14T11:34:53.933 に答える
1

RegisterHotKey が必要な場合もありますが、ほとんどの場合、システム全体のホットキーを使用したくないでしょう。私は次のようなコードを使用して終了しました:

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");
            }
        }
    }
}
于 2010-04-15T07:20:27.343 に答える
0

RegisterHotKey()Johnによって提案されたものは機能する可能性があります-唯一の落とし穴は、HWNDが必要なことです(を使用してPresentationSource.FromVisual()、結果をHwndSourceにキャストします)。

ただし、WM_HOTKEYメッセージに応答する必要もあります。WPFウィンドウのWndProcにアクセスする方法があるかどうかはわかりません(Windowsフォームウィンドウで実行できます)。

于 2008-09-08T03:03:06.683 に答える