軟件開發中,有時迫不得已要用到第三方的軟件,這時就涉及到在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("沒有找到窗口");
}