C# 使用C获取Windows 10中当前活动的应用程序名称#
我尝试获取当前活动的应用程序名(或进程名),但在某些应用程序(如Microsoft Edge)中,结果是ApplicationFrameHost。是否有方法获取应用程序名称,如在任务管理器中 我的实际代码:C# 使用C获取Windows 10中当前活动的应用程序名称#,c#,C#,我尝试获取当前活动的应用程序名(或进程名),但在某些应用程序(如Microsoft Edge)中,结果是ApplicationFrameHost。是否有方法获取应用程序名称,如在任务管理器中 我的实际代码: [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetWindowText(In
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
private string GetActiveProcess()
{
const int nChars = 256;
uint processId;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
GetWindowThreadProcessId(handle, out processId);
return Process.GetProcessById((int)processId).ProcessName;
}
return null;
}
我相信你要找的是:
Process.GetCurrentProcess().ProcessName
这将为您提供当前流程的名称此解决方案在表单应用程序中对我来说似乎很实用:
//aktivneOknoProces
string aktivneOknoProces = GetActiveProcess();
private string GetActiveProcess()
{
string app = "";
var foregroundProcess = Process.GetProcessById(WinAPIFunctions.GetWindowProcessId(WinAPIFunctions.GetforegroundWindow()));
if (foregroundProcess.ProcessName == "ApplicationFrameHost")
{
foregroundProcess = GetRealProcess(foregroundProcess);
}
if(foregroundProcess != null)
{
app = foregroundProcess.ProcessName;
}
return app;
}
private Process GetRealProcess(Process foregroundProcess)
{
WinAPIFunctions.EnumChildWindows(foregroundProcess.MainWindowHandle, ChildWindowCallback, IntPtr.Zero);
return _realProcess;
}
private bool ChildWindowCallback(IntPtr hwnd, IntPtr lparam)
{
var process = Process.GetProcessById(WinAPIFunctions.GetWindowProcessId(hwnd));
if (process.ProcessName != "ApplicationFrameHost")
{
_realProcess = process;
}
return true;
}
public class WinAPIFunctions
{
//Used to get Handle for Foreground Window
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr GetForegroundWindow();
//Used to get ID of any Window
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
public delegate bool WindowEnumProc(IntPtr hwnd, IntPtr lparam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr hwnd, WindowEnumProc callback, IntPtr lParam);
public static int GetWindowProcessId(IntPtr hwnd)
{
int pid;
GetWindowThreadProcessId(hwnd, out pid);
return pid;
}
public static IntPtr GetforegroundWindow()
{
return GetForegroundWindow();
}
}
然后请用解决方案创建一个答案-你甚至可以自己接受它。不要将“已解决”放在标题中-接受的答案将显示它已解决。Victor,如果您愿意,您可以复制我给出的答案(单击“编辑”,选择“全部”),并将其粘贴为您自己的答案。然后我会删除我的。你可以自己接受自己的答案,甚至可以获得更多的选票。