Click here to Skip to main content
16,011,757 members
Home / Discussions / C#
   

C#

 
QuestionClickonce deployment Pin
Wajihs10-Oct-06 1:14
Wajihs10-Oct-06 1:14 
AnswerRe: Clickonce deployment Pin
Judah Gabriel Himango10-Oct-06 5:12
sponsorJudah Gabriel Himango10-Oct-06 5:12 
QuestionQuestions on .NET Remoting Pin
Robert Rohde10-Oct-06 0:59
Robert Rohde10-Oct-06 0:59 
AnswerRe: Questions on .NET Remoting Pin
S. Senthil Kumar10-Oct-06 2:51
S. Senthil Kumar10-Oct-06 2:51 
AnswerRe: Questions on .NET Remoting Pin
sathish s10-Oct-06 3:18
sathish s10-Oct-06 3:18 
AnswerRe: Questions on .NET Remoting Pin
mav.northwind10-Oct-06 5:36
mav.northwind10-Oct-06 5:36 
QuestionHow to create a shortcut for my application Pin
CJayMeister10-Oct-06 0:38
CJayMeister10-Oct-06 0:38 
AnswerRe: How to create a shortcut for my application Pin
g00fyman10-Oct-06 1:24
g00fyman10-Oct-06 1:24 
you need to use system wide hook so that the os can intercept any key strokes and determine if it matches the ones you want then you process them and fire the application.

then you need a shortcut editor to change the shortcut by listening to the keys the user enters and rather than opening the program, assign it as the hotkey.

below is a class i found and adapted to suit my needs ( the class didn't have any copyright info in it and i can't remember where i found it, so i apologize if anyone is offended, although i did modify and improve it extensively )

DO NOT USE THIS CODE FOR MALICIOUS ACTIVITY, ELSE I WILL BE *VERY* DISSAPOINTED, AND YOU MAY GO TO HELL FOR IT!

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace GlobalKeyHook
{
  /// <summary>
  /// <c>KeyboardHook</c>, as the name implies, hooks into the windows messaging system to
  /// catch global keystrokes.
  /// </summary>
  /// <remarks>
  /// <para>	/// The hook is automatically released when the class is disposed.
  /// You can force the release by calling <see cref="Dispose"/></para>
  /// <para>The class exposes a KeyDown and KeyUp event, which can be used as any
  /// other keydown/up event in the .net framework. The sender object will always be
  /// this class, but all global keystrokes are processed.
  /// As in other keydown/up events, setting handled of the keyeventargs object to true
  /// <code>e.Handled=true;</code> will prevent other hooks from executing. For system keys
  /// as the Windows key, this means that the key gets 'blocked'</para>
  /// </remarks>
  public class KeyboardHook : IDisposable
  {
    #region Hook-dlls

    [DllImport("user32", EntryPoint = "SetWindowsHookExA")]
    private static extern int SetWindowsHookEx(int idHook, KeyBoardCatcherDelegate lpfn, int hmod, int dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto,
     ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
    private static extern short GetKeyState(int keyCode);

    [DllImport("user32", EntryPoint = "MapVirtualKey")]
    private static extern int MapVirtualKey(int wCode, int wMapType);

    [DllImport("user32", EntryPoint = "CallNextHookEx")]
    private static extern int CallNextHook(int hHook, int ncode, int wParam, KeybHookStruct lParam);

    private const int
      WH_KEYBOARD = 2,
      WH_KEYBOARD_LL = 13; //Global keyboard hook. 

    [DllImport("user32", EntryPoint = "UnhookWindowsHookEx")]
    private static extern int UnhookWindowsHookEx(int hHook);

    #endregion


    private bool m_DisableHooking = false;
    /// <summary>Gets/Sets the DisableHooking property.</summary>
    public bool DisableHooking
    {
      get { return m_DisableHooking; }
      set { m_DisableHooking = value; }
    }
	      

    public KeyboardHook()
    {
      kbcatcher = new KeyBoardCatcherDelegate(KeyBoardCatcher);

      keybhook = SetWindowsHookEx(WH_KEYBOARD_LL, kbcatcher,
        Marshal.GetHINSTANCE(typeof(KeyboardHook).Module).ToInt32(), 0);

      if (keybhook == 0)
        throw new ExternalException("Error: " + Marshal.GetLastWin32Error().ToString() + "\r\nCould not hook keyboard");
    }

    /// <summary></summary>
    /// <param name="AddModifierData" type="bool">See the property <see cref="AddModifierData"/> for info</param>
    /// <returns></returns>
    public KeyboardHook(bool AddModifierData)
      : this()
    {
      this.AddModifierData = AddModifierData;
    }

    #region Dispose
    /// <summary>The keyboard hook id, to be used with unhookwindowsex</summary>
    /// <remarks></remarks>
    private readonly int keybhook;

    private bool disposed;
    /// <summary>call Dispose when finished to release the hook.
    /// If this is not done manually, the destructor releases the hook,
    /// but manually disposing is more effective</summary>
    public void Dispose()
    {
      if (!disposed)
      {
        UnhookWindowsHookEx(keybhook);
        GC.SuppressFinalize(this);
        disposed = true;
      }
    }

    /// <summary>Destructor</summary>
    ~KeyboardHook()
    {
      Dispose();
    }
    #endregion

    /// <summary>This structure is filled when calling the KeyBoardCatcherDelegate.</summary>
    private struct KeybHookStruct
    {
      public int vkCode, scanCode, flags, time, dwExtraInfo;
    }

    private delegate int KeyBoardCatcherDelegate(int code, int wparam, ref KeybHookStruct lparam);


    public static bool CheckKeyPressed(params Keys[] keys)
    {
      for (int i = 0; i < keys.Length; i++)
        if (!CheckKeyPressed(ref keys[i])) return false;
      return true;
    }

    public static bool CheckKeyPressed(ref Keys key)
    {
      return CheckKeyPressed((int)key);
    }

    public static bool CheckKeyPressed(int vkey)
    {
      short ks = GetKeyState(vkey);
      Console.WriteLine(ks);
      return ks == 1;
    }

    public bool IsKeyPressed(Keys key)
    {
      return CheckKeyPressed(ref key);
    }

    public bool AreKeysPressed(params Keys[] keys)
    {
      return CheckKeyPressed(keys);
    }

    private const int HC_ACTION = 0;

    [MarshalAs(UnmanagedType.FunctionPtr)]
    private KeyBoardCatcherDelegate kbcatcher;

    /// <summary>Catch the keys if you like. These are the global keys. Set e.Handled=true to block the key (such as alt-tab)</summary>
    public event KeyEventHandler
      KeyDown = null,
      KeyUp = null;

    private const int
      wpKeyDown = 256,
      wpKeyUp = 257;

    /// <summary>If this value is <c>true</c>
    /// modifier data (such as shift,control,alt) is added to the KeyEventArgs, otherwise
    /// only the keydata is send.
    /// Adding the modifier data can produce some overhead since
    /// it is checked on every keypress.
    /// If you want to check manually, set this property to <c>false</c>
    /// and check <see cref="IsKeyPressed"/> instead
    /// </summary>
    public bool AddModifierData = true;

    public readonly Keys[] Modifiers = { Keys.Alt, Keys.Control, Keys.Shift };

    /// <summary>The method that's used to catch the keyboard input</summary>
    /// <param name="idHook" type="int"></param>
    /// <param name="wparam" type="int"></param>
    /// <param name="lparam" type="ref ShortCutter.Form1.keybHookStruct"></param>
    /// <returns></returns>
    private int KeyBoardCatcher(int hookcode, int wparam, ref KeybHookStruct lparam)
    {
      if (HC_ACTION == hookcode)
      {
        if ((wparam == wpKeyDown && KeyDown != null)
          || (wparam == wpKeyUp && KeyUp != null))
        {
          try
          {
            Keys k = (Keys)lparam.vkCode;
            if (AddModifierData)
              k |= Control.ModifierKeys;

            KeyEventArgs e = new KeyEventArgs(k);

            if (wparam == wpKeyDown)
              KeyDown(this, e);
            else
              KeyUp(this, e);
            //If handled, do not process any other hooks after this one. (key is blocked)
            if (e.Handled) return 1;
          }
          /*
          //for debugging only
          catch(Exception ex)
          {
            MessageBox.Show(ex.Message);
          }
          */
          catch { }
        }
      }
      //Call the next hook for the input
      return CallNextHook(keybhook, hookcode, wparam, lparam);
    }
  }
}


in your main init it like this

// install global system hooks
KeyHooker keyhooker = KeyHooker.Instance;


when you want to disable it so you can process the keys in the 'key editor' or 'key assignor', do this

// disable global keyboard hooks
KeyHooker.Instance.DisableHooking = true;


then re-enable them on form close or after the hot key is decided with this

// re-enable hotkey hooks
KeyHooker.Instance.DisableHooking = false;


hope that helps

g00fy
GeneralRe: How to create a shortcut for my application Pin
CJayMeister10-Oct-06 2:00
CJayMeister10-Oct-06 2:00 
Questionhow to take a screenShot using windows service Pin
Tariq Tario10-Oct-06 0:24
Tariq Tario10-Oct-06 0:24 
AnswerRe: how to take a screenShot using windows service Pin
g00fyman10-Oct-06 1:14
g00fyman10-Oct-06 1:14 
GeneralRe: how to take a screenShot using windows service Pin
Eric Dahlvang10-Oct-06 3:46
Eric Dahlvang10-Oct-06 3:46 
GeneralRe: how to take a screenShot using windows service Pin
Member 79236113-Jul-18 18:53
Member 79236113-Jul-18 18:53 
QuestionPassive/Active listening server Pin
The underdog9-Oct-06 23:53
The underdog9-Oct-06 23:53 
AnswerRe: Passive/Active listening server Pin
mikone10-Oct-06 0:01
mikone10-Oct-06 0:01 
GeneralRe: Passive/Active listening server Pin
The underdog10-Oct-06 0:26
The underdog10-Oct-06 0:26 
GeneralRe: Passive/Active listening server Pin
mikone10-Oct-06 0:56
mikone10-Oct-06 0:56 
GeneralRe: Passive/Active listening server Pin
The underdog10-Oct-06 2:23
The underdog10-Oct-06 2:23 
GeneralRe: Passive/Active listening server [modified] Pin
mikone10-Oct-06 2:52
mikone10-Oct-06 2:52 
QuestionGarbage Collector Performence Pin
Mandaar Kulkarni9-Oct-06 22:57
Mandaar Kulkarni9-Oct-06 22:57 
AnswerRe: Garbage Collector Performence Pin
quiteSmart9-Oct-06 23:16
quiteSmart9-Oct-06 23:16 
AnswerRe: Garbage Collector Performence Pin
S. Senthil Kumar10-Oct-06 2:55
S. Senthil Kumar10-Oct-06 2:55 
QuestionTabPage Events do not fire w/ .Net1.1 Pin
Jeff Jordan9-Oct-06 22:21
Jeff Jordan9-Oct-06 22:21 
AnswerRe: TabPage Events do not fire w/ .Net1.1 Pin
quiteSmart9-Oct-06 22:46
quiteSmart9-Oct-06 22:46 
GeneralRe: TabPage Events do not fire w/ .Net1.1 Pin
Jeff Jordan9-Oct-06 23:06
Jeff Jordan9-Oct-06 23:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.