C# Process Name, but not like 'chrome(.exe)' but like 'Chrome'
Maybe a weird question, but i did not really know how to ask it, hope i made my point clear in the title.
Code i have so far:
/// <summary>
/// Get the process that is currently running on the foreground
/// </summary>
/// <returns>Proces object containing all information about the process that is running on the foreground</returns>
public static Process GetCurrentRunningProcess()
{
Process[] processes = Process.GetProcesses();
IntPtr activeWindow = GetForegroundWindow();
foreach (Process process in processes)
{
if (process.MainWindowHandle == activeWindow)
return process;
}
return null;
}
/// <summary>
/// Get the Foreground Window using the user32.dll
/// </summary>
/// 开发者_StackOverflow中文版<returns>The handle of the window</returns>
[DllImport("user32", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();
This is what I'm doing right now, and it get's me the Process which contains a ProcessName. In my case I get 'chrome' where i actually want 'Chrome' or when I have notepad(.exe) i want Notepad. Is there a way to achieve this? Or do I have to make a list with program names and compare it with the ProcessName?
For the most part, a lookup table is better than trying to reformat the executable name as many programs are not named in the mosst obvious way (Microsoft Word is WINWORD.exe).
I haven't tested Process.MainWindowTitle
, but you may find that it includes the names of open documents and other rubbish you don't want. Best to test it before trying anything fancy.
What you can just use is Process.MainWindowTitle
What about replacing the "(.exe)" and casting the first letter to upper? Or do I miss the point?
public string ToUpperFirstLetter(string source)
{
if (String.IsNullOrEmpty(source))
return String.Empty;
// convert to char array of the string
var letters = source.Replace(".exe", String.Empty).ToCharArray();
// upper case the first char
letters[0] = Char.ToUpper(letters[0], CultureInfo.CurrentCulture);
// return the array made of the new char array
return new string(letters);
}
精彩评论