How to get the active application
I have the code to get the active window (for example notepad) and the capiton of the program (untitled - Notepad)
But now I want to get the application, cause if I save a file in notepad the capiton will change. And I need something unique, like the program name. I mean I can start notepad a zillion times, it will always be called notepad.
So does anyone know how to do this in C#?
[411 byte] By [
Ravashi] at [2007-12-24]
Once you get the process id using the code given in the other post you can use
GetProcessById to get the
Process object. From there you have access to everything that is exposed by the Win32 API. For uniqueness the
Id is the only valid indicator. Once a process closes there is nothing that makes it unique (not even the full path). What are you trying to do with the process once you get it?
Michael Taylor - 9/28/06
[DllImport("user32")]
privatestaticexternUInt32 GetWindowThreadProcessId(
Int32 hWnd, outInt32 lpdwProcessId
privateInt32 GetWindowProcessID(Int32 hwnd)
{
Int32 pid = 1;
GetWindowThreadProcessId(hwnd,out pid);
return pid;
}
string appProcessName =Process.GetProcessById(GetWindowProcessID(hwnd)).ProcessName;
string appExePath =Process.GetProcessById(GetWindowProcessID(hwnd)).MainModule.FileName;
string appExeName = appExePath.Substring(appExePath.LastIndexOf(@"\") + 1);
Thanks! that works :D
My total code for anybody else that needs it:
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 WindowsApplication1
{
publicpartialclassForm1 : Form
{
[DllImport("user32.dll")]
staticexternint GetForegroundWindow();
[
DllImport("user32")]
privatestaticextern
UInt32 GetWindowThreadProcessId(Int32 hWnd, out
Int32 lpdwProcessId);privateint
teller = 0;public
Form1()
{
InitializeComponent();
}privatevoid
timer1_Tick(object
sender, EventArgs e)
{
if
(teller == 1)
{
setTextje();
}
teller++;
}private
Int32 GetWindowProcessID(Int32 hwnd)
{
Int32 pid = 1;
GetWindowThreadProcessId(hwnd, out
pid);
return
pid;
}privatevoid
setTextje()
{
Int32 hwnd = 0;
hwnd = GetForegroundWindow();
string
appProcessName = Process.GetProcessById(GetWindowProcessID(hwnd)).ProcessName;
string
appExePath = Process.GetProcessById(GetWindowProcessID(hwnd)).MainModule.FileName;
string
appExeName = appExePath.Substring(appExePath.LastIndexOf(@"\") + 1);
textBox1.Text = appProcessName + " | " + appExePath + " | " + appExeName;
}
}
} You should keep a local var lastHwnd, or whatever.
int currentHwnd = GetForeGroundWindow();
if(currentHwnd != lastHwnd)
{
lastHwnd = currentHwnd;
///do the process stuff
}
Save on the process thrashing...