using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace SwitchProgram
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);
private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
public Form1()
{
InitializeComponent();
}
public struct WindowInfo
{
public IntPtr hWnd;
public string szWindowName;
public string szClassName;
}
List<WindowInfo> GetAllWindows()
{
List<WindowInfo> lwi = new List<WindowInfo>();
EnumWindows(delegate (IntPtr hWnd, int lparam)
{
WindowInfo wnd = new WindowInfo();
StringBuilder sb = new StringBuilder(256);
wnd.hWnd = hWnd;
GetWindowText(hWnd, sb, sb.Capacity);
wnd.szWindowName = sb.ToString();
GetClassName(hWnd, sb, sb.Capacity);
wnd.szClassName = sb.ToString();
Console.WriteLine("className=" + wnd.szClassName + ", windowText=" + wnd.szWindowName);
lwi.Add(wnd);
return true;
}, 0);
return lwi;
}
/// <summary>
/// 注意目标窗体应当选择应用程序的顶级窗体,比如对Borland程序而言,就是className为TApplication的窗体句柄。
/// </summary>
/// <param name="appWindowClassName"></param>
/// <param name="appWindowText"></param>
/// <returns></returns>
bool SwitchToApplication(string appWindowClassName, string appWindowText)
{
List<WindowInfo> lwi = GetAllWindows();
foreach (WindowInfo item in lwi)
{
if (item.szClassName == appWindowClassName && item.szWindowName == appWindowText)
{
SetForegroundWindow(item.hWnd);
ShowWindow(item.hWnd, 1);
return true;
}
}
return false;
}
private void button1_Click(object sender, EventArgs e)
{
SwitchToApplication("TApplication", "测试项目20171025");
}
}
}
上面描述了将指定应用程序切至前台的方法。只需要提供className, windowTextName即可。
这两个数据通过调试该程序即可得到。调试时会将系统所有的窗体信息输出至VS的输出窗口,在其中你可以找到对应的应用程序主窗体信息。
主窗体即便当前正在打开着模式对话框,这段代码同样能将模式对话框切至前台。