C# 查找其他应用程序并打开、显示、隐藏、关闭的API
软件开发中,有时迫不得已要用到第三方的软件,这时就涉及到在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("没有找到窗口");
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
2016-11-24 winform异步系统升级—BackgroundWorker