views:

166

answers:

3

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.

+3  A: 

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.

BrianLy
+1  A: 

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...

danbystrom
+1  A: 

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;
JohnB