title: Event handling in class file in C# windows application
body: <p>I am using the class pasted below to listen for the keypress event <kbd>ctrl</kbd> + <kbd>alt</kbd> + <kbd>q</kbd>.
  When I use the same code in a form, the event is firing and works well.
  But I need to use this function in a class file and keep that running in a thread, so that whenever the user does <kbd>ctrl</kbd> + <kbd>alt</kbd> + <kbd>q</kbd>, I get a confirmation box.</p>
  
  <p>Now the problem is, the keypress event is not firing!
  Is there any other way to make this code run in the background using a thread without using a form?</p>
  
  <pre><code>namespace sam1 
  {
    class LogoutManager
    {
        public static DialogResult Result;
        public static int allow;
  
        public void LogoutMgr()
        {
            KeyboardHook hook = new KeyboardHook();
            hook.KeyPressed += new EventHandler&lt;KeyPressedEventArgs&gt;(hook_KeyPressed);
            hook.RegisterHotKey((ModifierKeys)2 | (ModifierKeys)1, Keys.Q);
        }
  
        void hook_KeyPressed(object sender, KeyPressedEventArgs e)
        {
            if (allow == 0)
            {
                allow = allow + 1;
                Result = MessageBox.Show("Are you sure, you want to log off?", "Log off"
                        , MessageBoxButtons.YesNo
                        , MessageBoxIcon.Warning);
  
                if (Result == DialogResult.Yes)
                {
                    allow = 0;
                }
                else
                {
                    allow = 0;
                }
            }
        }
    }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>namespace sam1
  {
      public sealed class KeyboardHook : IDisposable
  {
      // Registers a hot key with Windows.
      [DllImport("user32.dll")]
      private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
      // Unregisters the hot key with Windows.
      [DllImport("user32.dll")]
      private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
  
      /// &lt;summary&gt;
      /// Represents the window that is used internally to get the messages.
      /// &lt;/summary&gt;
      private class Window : NativeWindow, IDisposable
      {
          private static int WM_HOTKEY = 0x0312;
  
          public Window()
          {
              // create the handle for the window.
              this.CreateHandle(new CreateParams());
          }
  
          /// &lt;summary&gt;
          /// Overridden to get the notifications.
          /// &lt;/summary&gt;
          /// &lt;param name="m"&gt;&lt;/param&gt;
          protected override void WndProc(ref Message m)
          {
              base.WndProc(ref m);
  
              // check if we got a hot key pressed.
              if (m.Msg == WM_HOTKEY)
              {
                  // get the keys.
                  Keys key = (Keys)(((int)m.LParam &gt;&gt; 16) &amp; 0xFFFF);
                  ModifierKeys modifier = (ModifierKeys)((int)m.LParam &amp; 0xFFFF);
  
                  // invoke the event to notify the parent.
                  if (KeyPressed != null)
                      KeyPressed(this, new KeyPressedEventArgs(modifier, key));
              }
          }
  
          public event EventHandler&lt;KeyPressedEventArgs&gt; KeyPressed;
  
          #region IDisposable Members
  
          public void Dispose()
          {
              this.DestroyHandle();
          }
  
          #endregion
      }
  
      private Window _window = new Window();
      private int _currentId;
  
      public KeyboardHook()
      {
          // register the event of the inner native window.
          _window.KeyPressed += delegate(object sender, KeyPressedEventArgs args)
          {
              if (KeyPressed != null)
                  KeyPressed(this, args);
          };
      }
  
      /// &lt;summary&gt;
      /// Registers a hot key in the system.
      /// &lt;/summary&gt;
      /// &lt;param name="modifier"&gt;The modifiers that are associated with the hot key.&lt;/param&gt;
      /// &lt;param name="key"&gt;The key itself that is associated with the hot key.&lt;/param&gt;
      public void RegisterHotKey(ModifierKeys modifier, Keys key)
      {
          // increment the counter.
          _currentId = _currentId + 1;
  
          // register the hot key.
          if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
              throw new InvalidOperationException("Couldn’t register the hot key.");
      }
  
      /// &lt;summary&gt;
      /// A hot key has been pressed.
      /// &lt;/summary&gt;
      public event EventHandler&lt;KeyPressedEventArgs&gt; KeyPressed;
  
      #region IDisposable Members
  
      public void Dispose()
      {
          // unregister all the registered hot keys.
          for (int i = _currentId; i &gt; 0; i--)
          {
              UnregisterHotKey(_window.Handle, i);
          }
  
          // dispose the inner native window.
          _window.Dispose();
      }
  
      #endregion
  }
  
  /// &lt;summary&gt;
  /// Event Args for the event that is fired after the hot key has been pressed.
  /// &lt;/summary&gt;
  public class KeyPressedEventArgs : EventArgs
  {
      private ModifierKeys _modifier;
      private Keys _key;
  
      internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
      {
          _modifier = modifier;
          _key = key;
      }
  
      public ModifierKeys Modifier
      {
          get { return _modifier; }
      }
  
      public Keys Key
      {
          get { return _key; }
      }
  }
  
  /// &lt;summary&gt;
  /// The enumeration of possible modifiers.
  /// &lt;/summary&gt;
  [Flags]
  public enum ModifierKeys : uint
  {
      Alt = 1,
      Control = 2,
      Shift = 4,
      Win = 8
  }
  
  }
  </code></pre>