避免程序重复启动,并且将已经启动的程序显示到窗体最前段。

上一篇介绍了一下怎么避免程序的重复启动

对于如何将已经启动的窗口再一次显示到最前面没有涉及到。

现在来说一下。

首先 添加一下命名空间:
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;

添加以下常量和引用:

public const int SW_HIDE = 0;//隐藏
  public const int SW_NORMAL = 1;//普通
  public const int SW_SHOWMINIMIZED = 2;//最小化
  public const int SW_SHOWMAXIMIZED = 3;//最大化

  [DllImport("User32.dll")]
  public static extern void SetForegroundWindow(IntPtr hwnd);

  [DllImport("User32.dll")]
  public static extern IntPtr GetForegroundWindow();

  [DllImport("User32.dll")]
  public static extern int GetWindowThreadProcessId(IntPtr hwnd, IntPtr pProcId);

  [DllImport("User32.dll")]
  public static extern bool AttachThreadInput(int idAttach, int idAttachTo, int fAttach);

  [DllImport("User32.dll")]
  public static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

在Main函数里添加一下代码(加粗字体部分

蓝色字体为程序名,也就是进程名


  static void Main(string[] args)
  {
   Process[] plist = Process.GetProcesses();
   int cid = Process.GetCurrentProcess().Id;

   for (int i = 0; i < plist.Length; i++)
   {
    if (cid != plist[i].Id)
    {
     string s = plist[i].ProcessName;
     if (s == @"MstProducts")
     {
      ShowWindowAsync(plist[i].MainWindowHandle, SW_NORMAL);                      
      SetForegroundWindow(plist[i].MainWindowHandle);
      return;
     }
    }
   }

   Application.Run(new frmProdMenu());
  }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值