如何获取系统中所有程序的句柄 - (第五十一讲)
这里给大家演示一种如何获取windows下所有应用程序的句柄。
运行结果如下,前面的数字就是句柄了,后面的是程序名称:

下面是一种简单的遍历程序名的一种方法,代码中,可以通过调用“p.Kill();”来将程序关闭掉。
List<string> str = new List<string>();
Process[] processes = Process.GetProcesses();
foreach (Process p in processes)
{
str.Add(p.ProcessName);
//p.Kill();// 关闭程序
}
str = str.OrderBy(x => x).ToList();
foreach (string s in str)
textBox2.Text += s + "\r\n";
还有一种稍微复杂一点的,可以获取到程序的句柄:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
#if false
List<string> str = new List<string>();
Process[] processes = Process.GetProcesses();
foreach (Process p in processes)
{
str.Add(p.ProcessName);
//p.Kill();// 关闭程序
}
str = str.OrderBy(x => x).ToList();
foreach (string s in str)
textBox2.Text += s + "\r\n";
#endif
// 获取程序的句柄
test.WindowInfo[] a = new test().GetAllDesktopWindows();
for (int i = 0; i < a.Length; i++)
{
if (a[i].szClassName.Contains("QQ")) // 获取QQ的句柄
textBox2.Text += a[i].hWnd + "," + a[i].szClassName + "\r\n";
}
}
}
public class test
{
private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);
//用来遍历所有窗口
[DllImport("user32.dll")]
private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);
//获取窗口Text
[DllImport("user32.dll")]
private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount);
//获取窗口类名
[DllImport("user32.dll")]
private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount);
//自定义一个类,用来保存句柄信息,在遍历的时候,随便也用空上句柄来获取些信息,呵呵
public struct WindowInfo
{
public IntPtr hWnd;
public string szWindowName;
public string szClassName;
}
public WindowInfo[] GetAllDesktopWindows()
{
//用来保存窗口对象 列表
List<WindowInfo> wndList = new List<WindowInfo>();
//enum all desktop windows
EnumWindows(delegate (IntPtr hWnd, int lParam)
{
WindowInfo wnd = new WindowInfo();
StringBuilder sb = new StringBuilder(256);
//get hwnd
wnd.hWnd = hWnd;
//get window name
GetWindowTextW(hWnd, sb, sb.Capacity);
wnd.szWindowName = sb.ToString();
//get window class
GetClassNameW(hWnd, sb, sb.Capacity);
wnd.szClassName = sb.ToString();
//add it into list
wndList.Add(wnd);
return true;
}, 0);
return wndList.ToArray();
}
}
}