C#如何调用外部程序,及该托盘程序的恢复与隐藏

来源:互联网 发布:软件开发自学 编辑:程序博客网 时间:2024/06/01 09:42

第一次写博客,太OUT了……

现状:项目中要调用一个外部的应用程序,该程序最小化之后,隐藏在系统托盘中

要求:如果该程序没有运行,则启动,如果被隐藏在托盘中,则恢复到使用状态

看了网上的资料,好多代码超级复杂,得码半天,

ShowWindow中的第二个参数: 0,表示隐藏,1表示正常显示,2表示最小化,3表示最大化


直接代码:

using System.Diagnostics;


         [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string className, string frmText);
        [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
        public static extern int ShowWindow(IntPtr hwnd, int showWay);
        public static IntPtr frmHwnd;

// 下面的代码,放到该放的地方去

  try
            {
                Process[] pros= Process.GetProcessesByName("程序进程名");
                if (pros.ToList().Count > 0)//存在该进程
                {
                    IntPtr handle = pros[0].MainWindowHandle;
                    if (handle.ToInt32() == 0)
                    {
                        frmHwnd= FindWindow(null, "窗体的text");
                        ShowWindow(frmHwnd,1);//显示窗体
                    }

                    else 
                    {
                        ShowWindow(handle, 0);//  隐藏窗体
                    }
                }
                else//不存在,则启动该程序
                {
                    string road = "程序路径";
                    ProcessStartInfo myStartInfo = new ProcessStartInfo();
                    myStartInfo.FileName = road;
                    Process myProc= new Process();
                    myProc.StartInfo = MyStarInfo;
                    myProc.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示");
            }

0 0