工作中一直感觉任务栏不够用,密密麻麻的,就想做一个可以将当前正在运行的应用程序以列表的形式展示出来(像开始菜单那样的)进行切换等操作,第一步就是模仿windows任务管理器显示正在运行的应用程序,但是试了很多种方法要么无法显示文件夹或磁盘,或者无法显示一些特殊的程序,比如金山的WPS2012,最后终于找到可以实现的方法,现在写出来分享一下。
[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", EntryPoint = "SetForegroundWindow")] public static extern int SetForegroundWindow(int hwnd); [DllImport("user32.dll")] private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize); private const int GW_HWNDFIRST = 0; private const int GW_HWNDNEXT = 2; private const int GWL_STYLE = (-16); private const int GWL_EXSTYLE = (-20); private const int WS_VISIBLE = 268435456; private const int WS_BORDER = 8388608; private const int WS_EX_TOOLWINDOW = (int)0x00000080; public List <string> GetRunApplicationList(Form appForm) { try { List <string> appString = new List <string>(); int handle = (int)appForm.Handle; int hwCurr; hwCurr = GetWindow(handle, GW_HWNDFIRST); while (hwCurr > 0) { int isTask = (WS_VISIBLE ); int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE); int lngStyleEx = GetWindowLongA(hwCurr,GWL_EXSTYLE); bool taskWindow = ((lngStyle & isTask) == isTask); bool taskWindowEx = ((lngStyleEx & WS_EX_TOOLWINDOW) != WS_EX_TOOLWINDOW);//加上这个判断后正常显示 if (taskWindow & taskWindowEx) { int length = GetWindowTextLength(new IntPtr(hwCurr)); StringBuilder sb = new StringBuilder(2 * length + 1); GetWindowText(hwCurr, sb, sb.Capacity); string strTitle = sb.ToString(); if (!string.IsNullOrEmpty(strTitle)) { appString.Add(strTitle); } } hwCurr = GetWindow(hwCurr, GW_HWNDNEXT); } return appString; } catch (Exception ex) { throw new ApplicationException("读取应用程序信息时出错:" + ex.Message); } } private void button1_Click(object sender, EventArgs e) { List<string> list=new List<string>(); list=GetRunApplicationList(this); foreach (var l in list) { textBox1.Text +=l+ "\r\n"; } }