winform

#region 标题移动
Point pt;
private void PLTitle_MouseDown(object sender, MouseEventArgs e)
{
pt = Cursor.Position;
}

private void PLTitle_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int px = Cursor.Position.X - pt.X;
int py = Cursor.Position.Y - pt.Y;
this.Location = new Point(this.Location.X + px, this.Location.Y + py);

pt = Cursor.Position;
}
}
#endregion

  1. static class Program
  2.  
    {
  3.  
    /// <summary>
  4.  
    /// 应用程序的主入口点。
  5.  
    /// </summary>
  6.  
    [ STAThread]
  7.  
    static void Main()
  8.  
    {
  9.  
    //0106add 一次打开一个应用程序
  10.  
    Process instance = RunningInstance();
  11.  
    if (instance != null)
  12.  
    {
  13.  
    if (instance.MainWindowHandle.ToInt32() == 0) //是否托盘化
  14.  
    {
  15.  
    MessageBox.Show( "程序已打开并托盘化");
  16.  
    return;
  17.  
    }
  18.  
    //1.2 已经有一个实例在运行
  19.  
    HandleRunningInstance(instance);
  20.  
    return;
  21.  
    }
  22.  
     
  23.  
    Application.EnableVisualStyles();
  24.  
    Application.SetCompatibleTextRenderingDefault( false);
  25.  
    Application.Run( new Form1());
  26.  
     
  27.  
    }
  28.  
     
  29.  
     
  30.  
     
  31.  
     
  32.  
    #region 确保程序只运行一个实例
  33.  
    private static Process RunningInstance()
  34.  
    {
  35.  
    Process current = Process.GetCurrentProcess();
  36.  
    Process[] processes = Process.GetProcessesByName(current.ProcessName);
  37.  
    //遍历与当前进程名称相同的进程列表
  38.  
    foreach (Process process in processes)
  39.  
    {
  40.  
    //如果实例已经存在则忽略当前进程
  41.  
    if (process.Id != current.Id)
  42.  
    {
  43.  
    //保证要打开的进程同已经存在的进程来自同一文件路径
  44.  
    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
  45.  
    {
  46.  
    //返回已经存在的进程
  47.  
    return process;
  48.  
    }
  49.  
    }
  50.  
    }
  51.  
    return null;
  52.  
    }
  53.  
    //3.已经有了就把它激活,并将其窗口放置最前端
  54.  
    private static void HandleRunningInstance(Process instance)
  55.  
    {
  56.  
    ShowWindowAsync(instance.MainWindowHandle, 1); //调用api函数,正常显示窗口
  57.  
    SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端
  58.  
    }
  59.  
    [ DllImport("User32.dll")]
  60.  
    private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
  61.  
    [ DllImport("User32.dll")]
  62.  
    private static extern bool SetForegroundWindow(System.IntPtr hWnd);
  63.  
    #endregion
  64.  

猜你喜欢

转载自www.cnblogs.com/zhaocha/p/9296323.html