2009-07-21 77 views
9

E.g.使用winamp(至少在Windows上),您可以在後臺使用winamp播放全屏遊戲,並使用媒體按鈕*來控制聲音。 Winamp不需要專注,讓遊戲繼續全屏。捕獲不帶焦點的按鍵

我更願意用Java編寫這個,但這可能不起作用(捕捉擊鍵沒有焦點已經很難在Java afaik中),所以任何C#解決方案也很好。

所以基本的問題是:如何捕捉沒有焦點的擊鍵?我相信'後退/前進/停止/郵件/搜索/收藏夾/網頁/首頁'按鈕被稱爲媒體按鈕,但更好的名字將受到歡迎:)。

+0

我打電話給他們的媒體按鈕或媒體鍵太多,不知道更好的名字。 – Luc 2014-01-09 17:34:07

回答

7

低級窗口掛鉤是一種方法。這裏有一個article,這裏有一些來自MSDN的更多信息。

這是一個什麼樣的代碼可以看起來像一個局部視圖:

private IntPtr LowLevelKeyboardHook(int nCode, WindowsMessages wParam, [In] KBDLLHOOKSTRUCT lParam) 
    { 
     bool callNext = true; 

     bool isKeyDown = (wParam == WindowsMessages.KEYDOWN || wParam == WindowsMessages.SYSKEYDOWN); 
     bool isKeyUp = (wParam == WindowsMessages.KEYUP || wParam == WindowsMessages.SYSKEYUP); 

     if ((nCode >= 0) && (isKeyDown || isKeyUp)) 
     { 
      // the virtual key codes and the winforms Keys have the same enumeration 
      // so we can freely cast back and forth between them 
      Keys key = (Keys)lParam.vkCode; 

      // Do your other processing here... 
     } 

     // if any handler returned false, trap the message 
     return (callNext) ? User32.CallNextHookEx(_mainHook, nCode, wParam, lParam) : _nullNext; 
    } 


    /// <summary> 
    /// Registers the user's LowLevelKeyboardProc with the system in order to 
    /// intercept any keyboard events before processed in the regular fashion. 
    /// This can be used to log all keyboard events or ignore them. 
    /// </summary> 
    /// <param name="hook">Callback function to call whenever a keyboard event occurs.</param> 
    /// <returns>The IntPtr assigned by the Windows's sytem that defines the callback.</returns> 
    private IntPtr RegisterLowLevelHook(LowLevelKeyboardProc hook) 
    { 
     IntPtr handle = IntPtr.Zero; 

     using (Process currentProcess = Process.GetCurrentProcess()) 
     using (ProcessModule currentModule = currentProcess.MainModule) 
     { 
      IntPtr module = Kernel32.GetModuleHandle(currentModule.ModuleName); 
      handle = User32.SetWindowsHookEx(HookType.KEYBOARD_LL, hook, module, 0); 
     } 

     return handle; 
    } 

    /// <summary> 
    /// Unregisters a previously registered callback from the low-level chain. 
    /// </summary> 
    /// <param name="hook">IntPtr previously assigned to the low-level chain. 
    /// Users should have stored the value given by 
    /// <see cref="Drs.Interop.Win32.LowLevelKeyboard.RegisterLowLevelHook"/>, 
    /// and use that value as the parameter into this function.</param> 
    /// <returns>True if the hook was removed, false otherwise.</returns> 
    private bool UnregisterLowLevelHook(IntPtr hook) 
    { 
     return User32.UnhookWindowsHookEx(hook); 
    } 

就實現所有的P/Invoke聲明必要的,它應該工作。 我在我的應用程序中使用這種方法,它工作正常。

+0

這些類型在我的應用程序中無法識別,它不能編譯(WindowsMessages,User32等等......)你做了什麼來使它工作?你有任何機會在任何地方在線代碼? – 2013-06-11 12:10:45

相關問題