Nike
Nike

Reputation: 1357

Is it possible to get the name of current active application

User can switch active application by Alt+Tab or by clicking on their icons in TaskBar. Is it possible to get the name (or other unique characteristic) of current active application?

I want to write a program which collects statistic of the applications usage.

Upvotes: 2

Views: 3664

Answers (3)

JohnB
JohnB

Reputation: 18982

To get the name of your c# application (several options):

(first one requires you to add reference System.Windows.Forms)

string name1 = System.Windows.Forms.Application.ExecutablePath;
string name2 = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location
string name3 = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string name4 = Environment.GetCommandLineArgs()[0];
string name5 = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
string name6 = System.Reflection.Assembly.GetEntryAssembly().CodeBase;
string name7 = System.Reflection.Assembly.GetEntryAssembly().FullName;

Upvotes: 1

Brian Lyttle
Brian Lyttle

Reputation: 14579

The Windows API has a function called GetForegroundWindow(). You will need to use P/Invoke to call into the Win32 API. The P/Invoke wiki has more info for C# users.

See this page for an example which gets the caption (name) of the current application.

Upvotes: 6

Dan Byström
Dan Byström

Reputation: 9244

You're looking for the API functions GetForegroundWindow and GetWindowText. There is also the GetWindowThreadProcessId function which will get the process id from the hWnd and then you can use the regular .NET classes for dealing with processes...

Upvotes: 1

Related Questions