获取当前激活窗口(顶置)
GetForegroundWindow()
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", EntryPoint = "GetWindowText")]
public static extern int GetWindowText(
int hwnd,
string lpString,
int cch
);
IntPtr hWnd = GetForegroundWindow();
//hWnd:窗口句柄。
获取进程和线程ID
GetWindowThreadProcessId
函数原型:
DWORD GetWindowThreadProcessId(HWND hWnd,LPDWORD lpdwProcessId);
参数说明:
hWnd:传入的窗口句柄;lpdwProcessId:返回的进程ID地址。
返回值:
函数返回的是窗口所属线程ID。
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
uint procId = 0;
uint id = GetWindowThreadProcessId(hWnd, out procId);
获取process
public static System.Diagnostics.Process GetProcessById (int processId);
通过process可以获取相应的属性,如名字,titile。
var proc = Process.GetProcessById((int)procId);
string titleName = proc.MainWindowTitle;
本文介绍如何使用C#调用Windows API函数GetForegroundWindow()和GetWindowThreadProcessId()来获取当前活动窗口的句柄及所属进程ID,并演示了如何通过进程ID获取进程对象及其属性。

2640

被折叠的 条评论
为什么被折叠?



