Ensuring that only a single instance of a C#.NET application is running

I ran into a scenario once were i didn’t want the user to be able to run more than one instance of a C# application, probably you have seen one setting in VB.NET, where you can make a single instance application, if not you can find that
under the project properties then in the application tab ..


Anyways, this option is not available in Visual C#.NET Project Properties !! and it looks like it have to be done programaticaly, the code that accomplishes this is in the Microsoft.VisualBasic namespace, and it can be used in a C# application, so a reference to the Microsoft.VisualBasic assembly is required in your C# application.
Another way to accomplish that (single app instance) is searching through the currently running processes for you application process and other processes that were launched form the same .exe file…
After trying a lot of choices any trying a lot of approaches , i ran into the Mutex class (short for “mutual exclusion”) , which is a Class from the System.Threading Namespace that can be used to keep processes from interfering with each other, and it requires less lines of code and less execution time.

Mutex Class:
Using the Mutex is a quick and a popular way to ensure only once instance is running , so just create a mutex in your program with a specific name,
here is the code to do this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
namespace My_Application
{
 static class Program
 {
 /// 
 /// The main entry point for the application.
 /// 
 [STAThread]
 static void Main()
 {
 
 bool ok;
 
 //Create and initializes a new instance of the Mutex class. 
 Mutex m = new Mutex(true, "My Application", out ok);
 
 if (!ok)
 {
  MessageBox.Show("Another instance is already running!");
  return;
 }
 
 Application.Run(new MyApp_Form());
 
 
 //Use the KeepAlive method of the GC Class
 GC.KeepAlive(m);
 
 }
 }
}

 

Notes:

  • In the Mutex constructor parameters:
    - The first parameter is set to true to give the calling thread initial ownership to the mutex.
    - The second parameter is the name of the mutex ( give it a unique name).
    - The third parameter is a boolean output variable that indicates if ownership was granted to the calling thread.
  • The KeepAlive method of the GC(Garbage Collector) Class performs no operation and produces no side effect other than extending the lifetime of the object passed in as a parameter.

Java Applet bar-chart & line-chart

Here is a Java applet that allows the user to enter as many numbers as desired and then displays the numbers in either bar-chart or line-chart form (the user’s values are the heights of the bars or the y-points on the graph). it also allows the user to switch between line and bar graph styles.

You need to download the JFree Chart class libraries first:
http://sourceforge.net/project/showfiles.php?group_id=15494&package_id=12428

You can make use of the following class libraries as well from mindviewinc.com:
http://www.mindviewinc.com/TIJ4/CodeInstructions.html

So here is the complete code:

 

import org.jfree.chart.*;
import org.jfree.data.category.*;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.*;
import org.jfree.data.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.plot.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import net.mindview.util.*;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.Box;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;
import javax.swing.JOptionPane;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
 
import static net.mindview.util.SwingConsole.*;
public class MyChart extends JApplet  {
  private JButton
    b = new JButton("View Bar-Chart"),
    l = new JButton("View Line-Chart");
 
  private JLabel lbl_Input = new JLabel("Enter Some Numbers(Seperated by a comma) ");
  private JTextField txt_Input = new JTextField(3);
 
 
  public void init()
  {
     lbl_Input.setLabelFor(txt_Input);
  
  JPanel TopPane = new JPanel(new GridLayout(0,1));
  TopPane.add(lbl_Input);
  TopPane.add(txt_Input);
  
  JPanel MiddlePane = new JPanel(new GridLayout(0,1));
  
  
 
  JPanel BottomPane = new JPanel();
  BottomPane.add(b);
  BottomPane.add(l);
  
  b.setSize(50, 50);
  l.setSize(50, 50);
  
  
  JPanel contentPane = new JPanel();
  contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  contentPane.setLayout(new BorderLayout());
  contentPane.add(TopPane, BorderLayout.NORTH);
  contentPane.add(MiddlePane, BorderLayout.CENTER);
  contentPane.add(BottomPane, BorderLayout.SOUTH);
  setContentPane(contentPane);
  
  add(TopPane, BorderLayout.NORTH);
  add(MiddlePane, BorderLayout.CENTER);
  add(BottomPane, BorderLayout.SOUTH);
 }
 public MyChart()
 {
      b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)  {
    
    String input = "";
    input = txt_Input.getText();
    
   
    
    int counter = 0;
    Scanner scanner = new Scanner(input);
    scanner.useDelimiter(",");
    while(scanner.hasNextInt())
    {
    counter ++; 
    scanner.nextInt();
    
    }
    
    
    int[] numbers = new int[counter];
    
    
    Scanner tempscanner = new Scanner(input);
    tempscanner.useDelimiter(",");
    while(tempscanner.hasNextInt())
     {
     
      for(int i = 0 ; i < counter; i++)
       numbers[i] = tempscanner.nextInt();
       
       
       
     }
    
    
    
    
    
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    
    for(int i = 0 ; i < counter ; i++)
      dataset.setValue(numbers[i], "Numbers", "" + numbers[i] );

    JFreeChart chart = ChartFactory.createBarChart
    ("Bar Chart ","", "", dataset, PlotOrientation.VERTICAL, false,true, false);
    chart.setBackgroundPaint(Color.gray);
    chart.getTitle().setPaint(Color.white);
    CategoryPlot p = chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.black);
    ChartFrame Chart_Frame=new ChartFrame("Bar Chart",chart);
    Chart_Frame.setVisible(true);
    Chart_Frame.setSize(400,350);
    
  
  
  
  
       }
    });
 
 
 
       l.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)  {
    
    String input = "";
    input = txt_Input.getText();
    
   
    
    int counter = 0;
    Scanner scanner = new Scanner(input);
    scanner.useDelimiter(",");
    while(scanner.hasNextInt())
    {
    counter ++; 
    scanner.nextInt();
    
    }
    
    
    int[] numbers = new int[counter];
    
    
    Scanner tempscanner = new Scanner(input);
    tempscanner.useDelimiter(",");
    while(tempscanner.hasNextInt())
     {
     
      for(int i = 0 ; i < counter; i++)
       numbers[i] = tempscanner.nextInt();
       
       
       
     }
    
    
    
    
    
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    
    for(int i = 0 ; i < counter ; i++)
      dataset.setValue(numbers[i], "Numbers", "" + numbers[i] );
            JFreeChart chart = ChartFactory.createLineChart
      ("Line Chart","", "", dataset, PlotOrientation.VERTICAL, false, true, false );
    
    chart.setBackgroundPaint(Color.white);
    final CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.black);
    
    
 
    ChartFrame Chart_Frame=new ChartFrame("Line Chart",chart);
    Chart_Frame.setVisible(true);
    Chart_Frame.setSize(400,350);
  
  
  
  
       }
    });
 
 
 
 
 
}
 public static void main(String[] args) {
    run(new MyChart(), 400, 200);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
}