1

With this code I can prevent a duplicate application from running the name given in the code .

But after the application is created, the name of that application (exe) can be changed and run multiple times in the same machine.

How to prevent it from running?

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Text = "Demo";
            int ac = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count();
            if (ac > 1)
            {
                MessageBox.Show("Application Already Running");
                this.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello World");
        }
    }
}```
carkod
  • 1,844
  • 19
  • 32
  • 1
    Does this answer your question? [What is the correct way to create a single-instance WPF application?](https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-wpf-application) – misticos Dec 07 '19 at 18:18
  • 1
    tldr; *system* (aka named) mutex or *system* (aka named) semaphore world well for this control between the same code running in different processes. It’s also sometimes an interview question :p – user2864740 Dec 07 '19 at 18:22
  • If you want Single Instance, follow above link. Do **not** Randomly kill Processes just because you want to be the only one named like that. Such behavior is between unwanted to Virus. – Christopher Dec 07 '19 at 18:44
  • 1
    A list of known methods here: [Correct .NET way to implement a single instance application](https://stackoverflow.com/q/14104988/7444103). My take, using a mix of mutex and UI Automation here: [Run the current application as Single Instance and show the previous instance](https://stackoverflow.com/a/50555532/7444103) – Jimi Dec 07 '19 at 18:46
  • [Single Instance Windows Form Application in C#](http://www.codescratcher.com/windows-forms/single-instance-windows-form-application-in-c/) – Mohamed Elrashid Dec 07 '19 at 20:11

0 Answers0