none
Detect the active application by mouse click RRS feed

  • Question

  • Hi all,

    I am writing an application in C# that is able to detect the current active application and noted down the application name in a file.

    so far by using below code I can get the current active application only:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    
    namespace ApplicationDetector
    {
        class Program
        {
            [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
            internal static extern IntPtr GetForegroundWindow();
    
            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
    
            public static string oldWindow = "";
            public static string currentWindow = "";
    
            static void Main(string[] args)
            {
                string newApplication = string.Empty;
                IntPtr activeWindow = GetForegroundWindow();
                List<String> strListProcesses = new List<string>();
                foreach (Process process in Process.GetProcesses())
                {
                    try
                    {
                        if (activeWindow == process.MainWindowHandle)
                        {
                            newApplication = process.MainWindowTitle;
                            Console.WriteLine(newApplication);
                        }
                    }
                    catch (System.ComponentModel.Win32Exception ex)
                    {
                        Console.WriteLine(ex.Message);
    
                    }
                }
                Application.Run();
            }
        }
    }

    but what i would like to have is, let's say a user is currently working on Word, and after a few mins, the user starts to working on Excel by mouse click the MS Excel, then the application should be able to detect that the user is currently using Excel.

    Friday, June 22, 2018 5:38 AM

Answers

  • Hello Andie,

    Are you going to do this?

    If so, you can refer below codes from Global window hook in C#

     public partial class Form1 : Form
        {
            delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
            WinEventDelegate dele = null;
            [DllImport("user32.dll")]
            static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
            private const uint WINEVENT_OUTOFCONTEXT = 0;
            private const uint EVENT_SYSTEM_FOREGROUND = 3;
    
            [DllImport("user32.dll")]
            static extern IntPtr GetForegroundWindow();
    
            [DllImport("user32.dll")]
            static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    
            private string GetActiveWindowTitle()
            {
                const int nChars = 256;
                IntPtr handle = IntPtr.Zero;
                StringBuilder Buff = new StringBuilder(nChars);
                handle = GetForegroundWindow();
    
                if (GetWindowText(handle, Buff, nChars) > 0)
                {
                    return Buff.ToString();
                }
                return null;
            }
    
            public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
            {
                //Log.Text += GetActiveWindowTitle() + "\r\n";  //Log= RichTextBox
                Log.Text = "The user is using " + GetActiveWindowTitle();
            }
    
            public Form1()
            {
                InitializeComponent();
                dele = new WinEventDelegate(WinEventProc);
                IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
            }
        }

    Hope this help you.

    Regards,

    Dolen


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by AndieDu Tuesday, June 26, 2018 1:01 AM
    Monday, June 25, 2018 6:54 AM

All replies

  • You aren't going to be able to do that with the code you posted. I guess if you wanted a poor man's solution you could call a function that had that logic frequently enough that you could try to monitor the changes but that is about it. In fact somebody has already posted some code for this.

    And here's another one over on GitHub.



    Michael Taylor http://www.michaeltaylorp3.net

    Friday, June 22, 2018 1:52 PM
    Moderator
  • It can be done with SetWinEventHook (P/Invoke) and EVENT_SYSTEM_FOREGROUND

    (tested on Windows 10)

    • Proposed as answer by phil chelis Tuesday, June 26, 2018 7:02 AM
    Friday, June 22, 2018 2:08 PM
  • thanks, will try and advise.
    Monday, June 25, 2018 2:57 AM
  • thanks, would you please post have some code
    Monday, June 25, 2018 2:57 AM
  • Hello Andie,

    Are you going to do this?

    If so, you can refer below codes from Global window hook in C#

     public partial class Form1 : Form
        {
            delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
            WinEventDelegate dele = null;
            [DllImport("user32.dll")]
            static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
            private const uint WINEVENT_OUTOFCONTEXT = 0;
            private const uint EVENT_SYSTEM_FOREGROUND = 3;
    
            [DllImport("user32.dll")]
            static extern IntPtr GetForegroundWindow();
    
            [DllImport("user32.dll")]
            static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    
            private string GetActiveWindowTitle()
            {
                const int nChars = 256;
                IntPtr handle = IntPtr.Zero;
                StringBuilder Buff = new StringBuilder(nChars);
                handle = GetForegroundWindow();
    
                if (GetWindowText(handle, Buff, nChars) > 0)
                {
                    return Buff.ToString();
                }
                return null;
            }
    
            public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
            {
                //Log.Text += GetActiveWindowTitle() + "\r\n";  //Log= RichTextBox
                Log.Text = "The user is using " + GetActiveWindowTitle();
            }
    
            public Form1()
            {
                InitializeComponent();
                dele = new WinEventDelegate(WinEventProc);
                IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
            }
        }

    Hope this help you.

    Regards,

    Dolen


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by AndieDu Tuesday, June 26, 2018 1:01 AM
    Monday, June 25, 2018 6:54 AM
  • Great, thanks so much Dolen, this is what i am after.
    Tuesday, June 26, 2018 1:01 AM