软件开发中,有时迫不得已要用到第三方的软件,这时就涉及到在C#应用程序需要对第三方软件打开、显示、隐藏以及关闭。
下面列举了几个常用的方式
打开应用程序,下面是2种简单用法:
第一种:
public enum ShowWindowCommands : int
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1, //用最近的大小和位置显示,激活
SW_NORMAL = 2,
SW_SHOWMINIMIZED = 3,
SW_SHOWMAXIMIZED = 4,
SW_MAXIMIZE = 5,
SW_SHOWNOACTIVATE = 6,
SW_SHOW = 7,
SW_MINIMIZE = 8,
SW_SHOWMINNOACTIVE = 9,
SW_SHOWNA = 10,
SW_RESTORE = 11,
SW_SHOWDEFAULT = 12,
SW_MAX = 13
}
[DllImport("shell32.dll")]
public static extern IntPtr ShellExecute(
IntPtr hwnd,
string lpszOp,
string lpszFile,
string lpszParams,
string lpszDir,
ShowWindowCommands FsShowCmd
);
ShellExecute(IntPtr.Zero, "open", @"D:\Program Files\OtherExe.exe", null, null, ShowWindowCommands.SW_SHOWMINIMIZED);
第二种:
Process myProcess = new Process();
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = @"D:\Program Files\OtherExe.exe";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
myProcess.Start();
而有时我们在打开其他软件时,又不想让其显示,只有在打开时将其隐藏掉了,虽然上面的例子中myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;涉及到窗口的显示状态,但有时并不是所想的那样显示,可能是本人水平有限,没有正确使用---。
下面我用到了另一种方式实现窗体的查找,隐藏及关闭
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int msg, uint wParam, uint lParam);
使窗体隐藏
IntPtr OtherExeWnd = new IntPtr(0);
OtherExeWnd = FindWindow("SunAwtFrame", null);
//判断这个窗体是否有效
if (OtherExeWnd != IntPtr.Zero)
{
Console.WriteLine("找到窗口");
ShowWindow(OtherExeWnd, 0);//0表示隐藏窗口
}
else
{
Console.WriteLine("没有找到窗口");
}
关闭窗体
IntPtr OtherExeWnd = new IntPtr(0);
OtherExeWnd = FindWindow("SunAwtFrame", null);
//判断这个窗体是否有效
if (OtherExeWnd != IntPtr.Zero)
{
Console.WriteLine("找到窗口");
SendMessage(OtherExeWnd, 16, 0, 0);//关闭窗口,通过发送消息的方式
}
else
{
Console.WriteLine("没有找到窗口");
}