C# 只能运行一个winForm进程

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows.Forms;

using System.Diagnostics;

using System.Runtime.InteropServices;

using System.Reflection;

 

namespace OnlyProcess

{

    static class Program

    {

        [STAThread]

        static void Main()

        {

            MessageBox.Show("ddddd");

            Process instance = RunningInstance();

            if (instance == null)

            {

                System.Windows.Forms.Application.EnableVisualStyles();    //这两行可以让窗体具有XP风格.

                System.Windows.Forms.Application.DoEvents();

                Application.Run(new Form1());

            }

            else

            {

                HandleRunningInstance(instance);

            }

        }

 

        #region   只运行一个实例

        public static Process RunningInstance()

        {

            Process current = Process.GetCurrentProcess();//当前新启动的线程

            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            //遍历与当前进程名称相同的进程列表

            foreach (Process process in processes)

            {

                //process,原来旧的线程与当前新启动的线程ID不一样

                //Ignore the current process

                if (process.Id != current.Id)

                {

                    //Make sure that the process is running from the exe file.

                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)

                    {

                        //Return the other process instance.

                        return process;//返回原来旧线程的窗体

                    }

                }

            }

            return null;

        }

        private static void HandleRunningInstance(Process instance)

        {

            MessageBox.Show("该应用系统已经在运行!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //调用api函数,正常显示窗口

            SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端。

        }

        [DllImport("User32.dll")]

        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);

        [DllImport("User32.dll")]

        private static extern bool SetForegroundWindow(System.IntPtr hWnd);

        private const int WS_SHOWNORMAL = 1;

        #endregion

    }

}

 

 

 

//namespace OnlyProcess

//{

//    static class Program

//    {

//        /// <summary>

//        /// 应用程序的主入口点。

//        /// </summary>

//        [STAThread]

//        static void Main()

//        {

//            //get the name of our process

//            string proc = Process.GetCurrentProcess().ProcessName;

//            //get the list of all processes by that name

//            Process[] processes = Process.GetProcessesByName(proc);

//            //if there is more than one process

//            if (processes.Length > 1)

//            {

//                DialogResult dr = MessageBox.Show("Application is already running! Are you sure want to run another?", "INFORMATION", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

 

//                if (dr == DialogResult.OK)

//                {

//                    Application.EnableVisualStyles();

//                    Application.SetCompatibleTextRenderingDefault(false);

//                    Application.Run(new Form1());

//                }

//            }

//            else

//            {

//                Application.EnableVisualStyles();

//                Application.SetCompatibleTextRenderingDefault(false);

//                Application.Run(new Form1());

//            }

//        }

//    }

//}

 

 

C# 创建互斥进程(程序) 互斥进程(程序), 简单点说,就是在系统中只能有该程序的一个实例运行. 现在很多软件都有这功能,如Maxthon 可以设置为"只允许打开一个窗体",还有Bitcomet等. 我也是看到这些软件的这个功能才来研究这个问题的. 要实现程序的互斥,通常有4中方式,下面用 C# 语言来实现:



实现方式一: 使用线程互斥变量. 通过定义互斥变量来判断是否已运行实例.C#实现如下:
把program.cs文件里的Main()函数改为如下代码:
static void Main()
{
bool runone;
System.Threading.Mutex run = new System.Threading.Mutex(true, "jiaao_test", out runone);
if (runone)
{
run.ReleaseMutex();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
MessageBox.Show("已经运行了一个实例了。");
}
}

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
C#中,如果你想要打开一个WinForms应用程序进程,并且需要向这个进程传递参数同时获取参数反馈,你可以使用多种方法。一种常见的方法是使用命令行参数,这样可以在应用程序启动时接收参数,并在程序运行时通过特定的方式返回结果。 下面是一个简单的例子,展示了如何启动一个WinForms应用程序,传递参数,并获取反馈: 1. 首先,在你的WinForms应用程序中,你需要处理命令行参数。你可以通过 `Environment.GetCommandLineArgs()` 方法获取启动应用程序的命令行参数数组。 2. 你还需要一个机制来传递参数和接收反馈。一个简单的方法是使用文件系统或命名管道来传递数据,或者使用更高级的IPC(进程间通信)技术,比如WCF服务、Windows消息队列(MSMQ)或共享内存。 3. 当你的应用程序接收到参数后,可以进行相应的处理,并将结果写入之前设定的通信机制中。 4. 在启动WinForms应用程序的主程序中,你需要等待被启动的进程完成任务,并从之前设定的通信机制中读取反馈结果。 这里是一个使用命令行参数启动WinForms应用程序的示例代码: ```csharp using System; using System.Diagnostics; using System.IO; class Program { static void Main(string[] args) { // 假设你的WinForms应用程序名为"WinFormsApp.exe",并且它处理命令行参数 string exePath = @"C:\Path\To\WinFormsApp.exe"; string[] processArgs = { "Hello", "World" }; // 你需要传递的参数 // 创建一个文件来存放结果,如果使用其他IPC机制则不需要这一步 string resultFilePath = Path.GetTempFileName(); // 构建完整的命令行参数字符串 string fullCommand = $"{exePath} {string.Join(" ", processArgs)} --result-file={resultFilePath}"; // 启动进程 ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = "cmd.exe", Arguments = $"/c {fullCommand}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); // 读取结果 string result = File.ReadAllText(resultFilePath); Console.WriteLine("Received Result: " + result); // 删除临时结果文件 File.Delete(resultFilePath); } } } ``` 在上述例子中,我们启动了一个名为 `WinFormsApp.exe` 的应用程序,并传递了两个参数 `"Hello"` 和 `"World"`,然后我们创建了一个临时文件来存放反馈结果。在应用程序执行完毕后,我们读取临时文件的内容作为结果。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值