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

  • SEARCH
  • Home
  • 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 8448067
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T10:19:45+00:00 2026-06-10T10:19:45+00:00

I would like to attach to a separate application (Microsoft Excel, for example), and

  • 0

I would like to attach to a separate application (Microsoft Excel, for example), and detect when a certain menu item is clicked (or a ribbon command in new versions, whatever).

I thought I could do it using the RegisterWindowMessage in user32.dll, but I have no clue which messages to intercept. Ideally, I would like to generalize this and detect something like:

"menu item XXX was clicked in the app YYY"

I found this CodeProject article which shows how to register hooks for events like creation of controls, application start/stop etc., but I couldn’t find an example of how to get button clicks or menu clicks.

Is this even possible? Am I on the right track, or I need to take a different approach?

  • 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-06-10T10:19:47+00:00Added an answer on June 10, 2026 at 10:19 am

    Alright, so I couldn’t resist the challenge here 🙂 Wrote a little program that does what you want.

    How it works : SetWindowsHookEx lets you place a global mouse hook. Now, you get the X, Y and then use WindowFromPoint to get the hWnd of your target window. From here you can do anything you like, in my case, I sent a WM_GETTEXT to get its title.

    This is what the program looks like implemented. Once you click Begin, it looks globally for Right Click events, and adds them to the listbox. Note : It NEEDS to be a window forms app, the hook will not work with a console app.

    enter image description here

    Usage (Just create a default WinForms project and change it to this):

     public partial class MainForm : Form
     {
        public MainForm()
        {
            InitializeComponent();
        }
        RMouseListener _native;
        private void button1_Click(object sender, EventArgs e)
        {//start
            _native = new RMouseListener();
            _native.RButtonClicked += 
                 new EventHandler<SysMouseEventInfo>(_native_RButtonClicked);
        }
        private void button2_Click(object sender, EventArgs e)
        {//stop
            _native.Close();
        }
        void _native_RButtonClicked(object sender, SysMouseEventInfo e)
        {
            listBox1.Items.Add(e.WindowTitle);
        }
    
    }
    

    Implementation (It’s a bit of code 😉 )

    public class SysMouseEventInfo : EventArgs
    {
        public string WindowTitle { get; set; }
    }
    public class RMouseListener
    {
        public RMouseListener()
        {
            this.CallBack += new HookProc(MouseEvents);
            //Module mod = Assembly.GetExecutingAssembly().GetModules()[0];
            //IntPtr hMod = Marshal.GetHINSTANCE(mod);
            using (Process process = Process.GetCurrentProcess())
            using (ProcessModule module = process.MainModule)
            {
                IntPtr hModule = GetModuleHandle(module.ModuleName);
                _hook = SetWindowsHookEx(WH_MOUSE_LL, this.CallBack, hModule, 0);
                //if (_hook != IntPtr.Zero)
                //{
                //    Console.WriteLine("Started");
                //}
            }
        }
        int WH_MOUSE_LL = 14;
        int HC_ACTION = 0;
        HookProc CallBack = null;
        IntPtr _hook = IntPtr.Zero;
    
        public event EventHandler<SysMouseEventInfo> RButtonClicked;
    
        int MouseEvents(int code, IntPtr wParam, IntPtr lParam)
        {
            //Console.WriteLine("Called");
    
            if (code < 0)
                return CallNextHookEx(_hook, code, wParam, lParam);
    
            if (code == this.HC_ACTION)
            {
                // Left button pressed somewhere
                if (wParam.ToInt32() == (uint)WM.WM_RBUTTONDOWN)
                {
                    MSLLHOOKSTRUCT ms = new MSLLHOOKSTRUCT();
                    ms = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                    IntPtr win = WindowFromPoint(ms.pt);
                    string title = GetWindowTextRaw(win);
                    if (RButtonClicked != null)
                    {
                        RButtonClicked(this, new SysMouseEventInfo { WindowTitle = title });
                    }
                }
            }
            return CallNextHookEx(_hook, code, wParam, lParam);
        }
    
        public void Close()
        {
            if (_hook != IntPtr.Zero)
            {
                UnhookWindowsHookEx(_hook);
            }
        }
        public delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
    
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetWindowsHookEx", SetLastError = true)]
        public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);
    
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
    
        [System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern IntPtr GetModuleHandle(string lpModuleName);
    
        [DllImport("user32.dll")]
        static extern IntPtr WindowFromPoint(int xPoint, int yPoint);
    
        [DllImport("user32.dll")]
        static extern IntPtr WindowFromPoint(POINT Point);
    
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool UnhookWindowsHookEx(IntPtr hhk);
    
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [Out] StringBuilder lParam);
    
        public static string GetWindowTextRaw(IntPtr hwnd)
        {
            // Allocate correct string length first
            //int length = (int)SendMessage(hwnd, (int)WM.WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
            StringBuilder sb = new StringBuilder(65535);//THIS COULD BE BAD. Maybe you shoudl get the length
            SendMessage(hwnd, (int)WM.WM_GETTEXT, (IntPtr)sb.Capacity, sb);
            return sb.ToString();
        }
    }
    [StructLayout(LayoutKind.Sequential)]
    public struct MSLLHOOKSTRUCT
    {
        public POINT pt;
        public int mouseData;
        public int flags;
        public int time;
        public UIntPtr dwExtraInfo;
    }
    enum WM : uint
    {//all windows messages here
        WM_RBUTTONDOWN = 0x0204,
        WM_GETTEXT = 0x000D,
        WM_GETTEXTLENGTH = 0x000E
    }
    
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    
        public POINT(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I use Runtime.getRuntime().exec() to execute my native cpp application and would like to attach/debug
In my WPF application I would like to attach an input gesture to a
I would like to attach an error to a formItem. In spark, it appears
I have a well div, and I would like to attach a small text/image
For every Card, I would like to attach a special number to them that
i would like to attach html controls like textboxes to a midi controller, is
I am using Linq-To-SQL and I would like to attach an interface to each
I have one PHP5 object passing messages to another, and would like to attach
I have console application and would like to run it as Windows service. VS2010
I would like to attach screen or tmux inside emacs, in shell mode. I

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.