2012-01-18 3 views
8

Sto cercando registrare un tasto di scelta rapida, sto traducendo codice this C++, ho scritto:come usare RegisterHotKey() in C#?

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Runtime.InteropServices; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     [DllImport("user32.dll")] 
     public static extern 
      bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, int vk); 
     [DllImport("user32")] 
     public static extern 
      bool GetMessage(ref Message lpMsg, IntPtr handle, uint mMsgFilterInMain, uint mMsgFilterMax); 

     public const int MOD_ALT = 0x0001; 
     public const int MOD_CONTROL = 0x0002; 
     public const int MOD_SHIFT = 0x004; 
     public const int MOD_NOREPEAT = 0x400; 
     public const int WM_HOTKEY = 0x312; 
     public const int DSIX = 0x36; 

     static void Main(string[] args) 
     { 
      if (!RegisterHotKey(IntPtr.Zero, 1, MOD_ALT | MOD_NOREPEAT, DSIX)) 
      { 
       Console.WriteLine("failed key register!"); 
      } 

      Message msg = new Message(); 

      while (!GetMessage(ref msg, IntPtr.Zero, 0, 0)) 
      { 
       if (msg.message == WM_HOTKEY) 
       { 
        Console.WriteLine("do work.."); 
       } 
      } 

      Console.ReadLine(); 
     } 
    } 

    public class Message 
    { 
     public int message { get; set; } 
    } 
} 

ma RegisterHotKey() mai restituisce false. Non sono sicuro degli argomenti passati nel metodo, IntPtr.Zero deve essere equivalente a null e la classe messaggio deve essere l'oggetto richiesto nel secondo argomento. qualcuno può chiarire per favore? qualsiasi aiuto è bene accetto!

+0

vedi [questa] (http://bloggablea.wordpress.com/ 2007/05/01/global-hotkeys-with-net /) – Shai

+0

NOTA: il valore per MOD_NOREPEAT è errato. https://msdn.microsoft.com/en-us/library/windows/desktop/ms646309(v=vs.85).aspx –

+0

L'esempio funziona perfettamente se si utilizza il valore costante corretto per MOD_NOREPEAT e il corretto GetMessage() definizione (che restituisce un int e utilizza la struttura MSG dallo spazio dei nomi System.Windows.Interop) – tigrou

risposta

1

Questo potrebbe aiutare:

Hotkey in console app

In sostanza, è necessario creare un modulo "nascosto" per farlo funzionare