[DllImport("user32", SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("User32.dll")]
extern static IntPtr GetForegroundWindow();
[DllImport("User32")]
private extern static int GetWindow(int hWnd, int wCmd);
[DllImport("User32")]
private extern static int GetWindowLongA(int hWnd, int wIndx);
[DllImport("user32", CharSet = CharSet.Auto)]
private extern static int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);
[DllImport("user32.dll")]
private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);
[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);
[DllImport("user32")]
public extern static int GetWindowThreadProcessId(IntPtr hWnd, ref int lpdwProcessId);
public struct WindowInfo
{
public IntPtr hWnd;
public string szWindowName;
public string szClassName;
}
private const int GW_HWNDFIRST = 0;
private const int GW_HWNDNEXT = 2;
private const int GWL_STYLE = (-16);
private const int WS_VISIBLE = 268435456;
private const int WS_BORDER = 8388608;
private static String GetModuleNameFromHandle(IntPtr hwnd)
{
int pId = 0;
GetWindowThreadProcessId(hwnd, ref pId);
return Process.GetProcessById(pId).MainModule.ModuleName;
}
//返回包含searchStr的进程的数量
public static int GetRunApplicationList(string searchStr)
{
List<String> appString = new List<String>();
Form f = new Form();
if (string.IsNullOrEmpty(searchStr) || searchStr.Trim() == "")
{
return 0;
}
try
{
int handle = (int)f.Handle;
int hwCurr;
hwCurr = GetWindow(handle, GW_HWNDFIRST);
while (hwCurr > 0)
{
int isTask = (WS_VISIBLE | WS_BORDER);
int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE);
bool taskWindow = ((lngStyle & isTask) == isTask);
if (taskWindow)
{
int length = GetWindowTextLength(new IntPtr(hwCurr));
StringBuilder sb = new StringBuilder(2 * length + 1);
GetWindowText(hwCurr, sb, sb.Capacity);
String strTitle = sb.ToString();
String moduleName = GetModuleNameFromHandle(new IntPtr(hwCurr));
//プランインポート
if (!string.IsNullOrEmpty(strTitle))
{
if (moduleName.IndexOf(searchStr) >= 0)
{
appString.Add(strTitle);
}
}
}
hwCurr = GetWindow(hwCurr, GW_HWNDNEXT);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
f.Dispose();
}
return appString.Count;
}
C#取得正在运行的程序的数量
最新推荐文章于 2021-12-24 16:45:35 发布