Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 278523
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T01:15:09+00:00 2026-05-12T01:15:09+00:00

I am using the class pasted below to listen for the keypress event ctrl

  • 0

I am using the class pasted below to listen for the keypress event ctrl + alt + q.
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 ctrl + alt + q, I get a confirmation box.

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?

namespace sam1 
{
  class LogoutManager
  {
      public static DialogResult Result;
      public static int allow;

      public void LogoutMgr()
      {
          KeyboardHook hook = new KeyboardHook();
          hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(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;
              }
          }
      }
  }
}

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

    /// <summary>
    /// Represents the window that is used internally to get the messages.
    /// </summary>
    private class Window : NativeWindow, IDisposable
    {
        private static int WM_HOTKEY = 0x0312;

        public Window()
        {
            // create the handle for the window.
            this.CreateHandle(new CreateParams());
        }

        /// <summary>
        /// Overridden to get the notifications.
        /// </summary>
        /// <param name="m"></param>
        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 >> 16) & 0xFFFF);
                ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);

                // invoke the event to notify the parent.
                if (KeyPressed != null)
                    KeyPressed(this, new KeyPressedEventArgs(modifier, key));
            }
        }

        public event EventHandler<KeyPressedEventArgs> 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);
        };
    }

    /// <summary>
    /// Registers a hot key in the system.
    /// </summary>
    /// <param name="modifier">The modifiers that are associated with the hot key.</param>
    /// <param name="key">The key itself that is associated with the hot key.</param>
    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.");
    }

    /// <summary>
    /// A hot key has been pressed.
    /// </summary>
    public event EventHandler<KeyPressedEventArgs> KeyPressed;

    #region IDisposable Members

    public void Dispose()
    {
        // unregister all the registered hot keys.
        for (int i = _currentId; i > 0; i--)
        {
            UnregisterHotKey(_window.Handle, i);
        }

        // dispose the inner native window.
        _window.Dispose();
    }

    #endregion
}

/// <summary>
/// Event Args for the event that is fired after the hot key has been pressed.
/// </summary>
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; }
    }
}

/// <summary>
/// The enumeration of possible modifiers.
/// </summary>
[Flags]
public enum ModifierKeys : uint
{
    Alt = 1,
    Control = 2,
    Shift = 4,
    Win = 8
}

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T01:15:09+00:00Added an answer on May 12, 2026 at 1:15 am

    What is the KeyboardHook class?

    Without knowing that class, I can only guess: the problem is probably that in Windows, keyboard shortcuts (as other events) are distributed via Window Messages, and Window Messages are usually received via Windows. A Form is a Window, therefore it can receive keyboard events.

    Since you already know it works with a Form, why not create a Form to handle this, but make it invisible? Then the form can react on the keyboard event and pass it on to an instance of your class.

    Does this solve your problem?

    Edit after reading your comments and update:
    Okay, KeyboardHook derives from NativeWindow; that means, it itself already is a window – no need for a Form.

    What you need, however, is an application loop. You start that via Application.Run. Then you create your KeyboardHook instance on the same thread that runs the message loop.

    The easiest way to do this is if you already have a main form – just pass that main form in to Application.Run, then do everything from your main form’s OnLoad method.

    If you have an application without any forms at all, you can use the Application.Run overload that does not require a Form, like this:

    Application.Idle += Initialize;
    Application.Run();
    ...
    
    private void Initialize (object sender, EventArgs e) 
    { 
      Application.Idle -= Initialize; 
      _hook = new KeyboardHook();
    
      // this must be performed from the thread running Application.Run!
      // do not move it out of this event handler
      _hook.RegisterHotKey (...);      
    }
    

    Note that you will need to stop the UI thread using Application.Exit, and also note that the thread calling Application.Run is blocked until Application.Exit is called. Run your other logic from a parallel thread.

    Be aware that KeyboardHook’s events will always be called on the thread that called Application.Run – this can easily lead to cross-threading problems; your code needs to be hardened for multi-threading. (Use the lock statement, and use it correctly.)

    In addition, KeyboardHook’s methods must only be called from the thread that called Application.Run. Therefore, use Application’s Idle event to do so.

    Windows Forms + threading is a very complex topic, and it’s easy to get it wrong.

    Fabian

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 135k
  • Answers 135k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Most thread APIs work by asking the operating system to… May 12, 2026 at 7:01 am
  • Editorial Team
    Editorial Team added an answer Here's the proper way to handle that cast. Edit: There… May 12, 2026 at 7:01 am
  • Editorial Team
    Editorial Team added an answer Prevent controls from being dragged onto the header area, period… May 12, 2026 at 7:01 am

Related Questions

I am using NHibernate to as the Data Access layer for my ASP.NET MVC
On my laptop with Intel Pentium dual-core processor T2370 (Acer Extensa) I ran a
I am attempting to create a small application to collect data received from an
As someone new to GUI development in Python (with pyGTK), I've just started learning

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.