Get the current active application name
Asked Answered
F

1

8

I want to get name of currently active application when my timer stops. After recording of 20 secs it should show me current active application name. I tried some code. You can see here. But it's not showing me anything after timer stops.

C# code:

public class Win32wrapper 
{
    private System.Timers.Timer pingTimer;
    private Timer recordTimer;

    private List<HarvestApp.ProcessInformation> ProcessList = new List<HarvestApp.ProcessInformation>();

    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint processId);

    private DateTime recordStartTime;

    public void startTimer(int pingTimerValue=5000, int recordTimerValue=20000)
    {

        pingTimer = new System.Timers.Timer(pingTimerValue);
        pingTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        pingTimer.Interval = pingTimerValue;
        pingTimer.Enabled = true;

        recordTimer = new Timer(recordTimerValue);
        recordTimer.Elapsed += new ElapsedEventHandler(OnRecordEvent);
        recordTimer.Interval = recordTimerValue;
        recordTimer.Enabled = true;

        recordStartTime = DateTime.Now;
    }

    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Ping Elapsed event was raised at {0}", e.SignalTime);


        //Record through win32dll the application foreground caption

        GetActiveFileNameTitle();

        //Store into collection object, Push into ArrayList, Push into process id
    }


    public String GetActiveFileNameTitle()
    {
        IntPtr hWnd = GetForegroundWindow();
        uint processId;
        GetWindowThreadProcessId(hWnd, out processId);
        Process p = Process.GetProcessById((int)processId);
        //p.MainModule.FileName.Dump();
        return p.ProcessName;
    }

        private void OnRecordEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Record Elapsed event was raised at {0}", e.SignalTime);

        ProcessInformation procTemp = GetMaxRunTimeForApplicationsBetween(recordStartTime, DateTime.Now);
        Harvest_TimeSheetEntry tempEntry = new Harvest_TimeSheetEntry(procTemp, recordStartTime, DateTime.Now);

        //Add to the list of the specific day Only not the entire
       // Globals._globalController.harvestManager._TIMESHEETENTRYDICTIONARY[recordStartTime.Date].Add(tempEntry);


        Globals._globalController.getDayViewWindow.Dispatcher.BeginInvoke(new Action(delegate()
        {
            Globals._globalController.getDayViewWindow.addHarvestEntrytoView(tempEntry);
         }));
        //Clean Out the ProcessList?

        recordStartTime = DateTime.Now;
    }


    public void stopTimer()
    {
        pingTimer.Stop();
        recordTimer.Stop();
    }
Freestyle answered 27/6, 2013 at 13:56 Comment(8)
Do you want to know the title of the current window? #116368Drobman
I want name of application. If notepad is running in the background then, it should show me name as "Notepad" there.Freestyle
The question is: do you want the window title or the process name of the foreground app?Mancini
What does this have to do with WPF?Fari
@Zicore I don't want window title. I want Name of process which is currently active. When I run my application, if Paint is active then, it's name (I.e Paint) should appear after 20 secs of timer starts.Freestyle
Have a look at my answer, working on an example right now...Mancini
@Zicore I tried this.But it's not working.Freestyle
Have a look to my edit, it seems you miss the usage of return value.Mancini
M
16

Edit: Title is missleading.

Watch your Code:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Ping Elapsed event was raised at {0}", e.SignalTime);

    //Record through win32dll the application foreground caption

    // You miss the output or usage of the return value here.
    GetActiveFileNameTitle();
    // Try 
    var procName = GetActiveFileNameTitle();
    Console.WriteLine(procName);

    //Store into collection object, Push into ArrayList, Push into process id
}

Working example:

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

to get the Foreground Window and:

[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

To determine the ProcessID. With the ProcessID you're able to obtain the name of the process. With the Process Class: http://msdn.microsoft.com/de-de/library/system.diagnostics.process.mainmodule.aspx

class Program
{
    static void Main(string[] args)
    {
        Thread.Sleep(5000); // Test it with 5 Seconds, set a window to foreground, and you see it works!
        IntPtr hWnd = GetForegroundWindow();
        uint procId = 0;
        GetWindowThreadProcessId(hWnd, out procId);
        var proc = Process.GetProcessById((int)procId);
        Console.WriteLine(proc.MainModule);
        Console.ReadKey();
    }

    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
}
Mancini answered 27/6, 2013 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.