简体   繁体   中英

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.

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.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM