<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tony Williams &#187; .Net</title>
	<atom:link href="http://blog.tonywilliams.me.uk/tag/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tonywilliams.me.uk</link>
	<description></description>
	<lastBuildDate>Tue, 10 Jan 2012 12:31:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Single instance app in WPF 4 with argument passing</title>
		<link>http://blog.tonywilliams.me.uk/single-instance-app-in-wpf-4-with-argument-passing/</link>
		<comments>http://blog.tonywilliams.me.uk/single-instance-app-in-wpf-4-with-argument-passing/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 13:08:03 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 4]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[WPF 4]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=26</guid>
		<description><![CDATA[How to have a WPF app with only 1 instance with only C# code and argument passing.]]></description>
			<content:encoded><![CDATA[<p>Extracted from: <a href="http://random.tonywilliams.me.uk/post/483779269/single-instance-app-in-wpf-4-with-argument-passing">http://random.tonywilliams.me.uk/post/483779269/single-instance-app-in-wpf-4-with-argument-passing</a></p>
<div>
<p>I was building a WPF app that required the use of JumpLists; the thing with JumpLists is that it calls your app&#8217;s exe with an argument which in turn creates a new instance of your app.</p>
<p>After a quick bit of googling I found a link [now dead] some code that restricts an app to a signle instance by using a mutex and passes the command argument supplied via named pipes.</p>
<p>Only portions of the code was recoverable, the rest I created my self.</p>
<p>Note that the code uses the .Net 4 Tasks, this can be replaced with threads if you want to use it in .Net 3.5. This also only passes the first argument through but can be easily changed to pass multiple.</p>
<pre class="brush:c#">namespace Your.App
{
  using System;
  using System.IO;
  using System.IO.Pipes;
  using System.Threading;
  using System.Threading.Tasks;

  public class SingleInstance : IDisposable
  {
    private readonly bool ownsMutex;
    private Mutex mutex;
    private Guid identifier;

    /// &lt;summary&gt;
    /// Occurs when [arguments received].
    /// &lt;/summary&gt;
    public event EventHandler&lt;GenericEventArgs&lt;string&gt;&gt; ArgumentsReceived;

    /// &lt;summary&gt;
    /// Initializes a new instance of the &lt;see cref="SingleInstance"/&gt; class.
    /// &lt;/summary&gt;
    /// &lt;param name="id"&gt;The id.&lt;/param&gt;
    public SingleInstance(Guid id)
    {
      this.identifier = id;
      mutex = new Mutex(true, identifier.ToString(), out ownsMutex);
    }

    /// &lt;summary&gt;
    /// Gets a value indicating whether this instance is first instance.
    /// &lt;/summary&gt;
    /// &lt;value&gt;
    /// 	&lt;c&gt;true&lt;/c&gt; if this instance is first instance; otherwise, &lt;c&gt;false&lt;/c&gt;.
    /// &lt;/value&gt;
    public bool IsFirstInstance
    {
      get
      {
        return ownsMutex;
      }
    }

    /// &lt;summary&gt;
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// &lt;/summary&gt;
    public void Dispose()
    {
      if (mutex != null &amp;&amp; ownsMutex)
      {
        mutex.ReleaseMutex();
        mutex = null;
      }
    }

    /// &lt;summary&gt;
    /// Passes the arguments to first instance.
    /// &lt;/summary&gt;
    /// &lt;param name="argument"&gt;The argument.&lt;/param&gt;
    public void PassArgumentsToFirstInstance(string argument)
    {
      using (var client = new NamedPipeClientStream(identifier.ToString()))
      using (var writer = new StreamWriter(client))
      {
        client.Connect(200);
        writer.WriteLine(argument);
      }
    }

    /// &lt;summary&gt;
    /// Listens for arguments from successive instances.
    /// &lt;/summary&gt;
    public void ListenForArgumentsFromSuccessiveInstances()
    {
      Task.Factory.StartNew(() =&gt;
                              {

                                using (var server = new NamedPipeServerStream(identifier.ToString()))
                                using (var reader = new StreamReader(server))
                                {
                                  while (true)
                                  {
                                    server.WaitForConnection();

                                    var argument = string.Empty;
                                    while (server.IsConnected)
                                    {
                                      argument += reader.ReadLine();
                                    }

                                    CallOnArgumentsReceived(argument);
                                    server.Disconnect();
                                  }
                                }
                              });
    }

    /// &lt;summary&gt;
    /// Calls the on arguments received.
    /// &lt;/summary&gt;
    /// &lt;param name="state"&gt;The state.&lt;/param&gt;
    public void CallOnArgumentsReceived(object state)
    {
      if (ArgumentsReceived != null)
      {
        if (state == null)
        {
          state = string.Empty;
        }

        ArgumentsReceived(this, new GenericEventArgs&lt;string&gt;() { Data = state.ToString() });
      }
    }
  }
}</pre>
<p>Here is the Generic Event Args class</p>
<pre class="brush:c#">namespace Your.App
{
  using System;

  public class GenericEventArgs&lt;TEventDataType&gt; : EventArgs
  {
    /// &lt;summary&gt;
    /// Gets or sets the data.
    /// &lt;/summary&gt;
    /// &lt;value&gt;The data.&lt;/value&gt;
    public TEventDataType Data { get; set; }
  }
}</pre>
<p>To use this class create an instance with a GUID for your app like so:</p>
<pre class="brush:c#">private static readonly SingleInstance SingleInstance = new SingleInstance(new Guid("24D910A1-1F03-44BA-85A0-BE7BC2655FFE"));</pre>
<p>Then on Application_Startup run your logic for it</p>
<pre class="brush:c#">private void Application_Startup(object sender, StartupEventArgs e)
{
  if (SingleInstance.IsFirstInstance)
  {
    SingleInstance.ArgumentsReceived += SingleInstanceParameter;
    SingleInstance.ListenForArgumentsFromSuccessiveInstances();
	// Do your other app logic
  }
  else
  {
    // if there is an argument available, fire it
    if (e.Args.Length &gt; 0)
    {
      SingleInstance.PassArgumentsToFirstInstance(e.Args[0]);
    }

    Environment.Exit(0);
  }
}

static void SingleInstanceParameter(object sender, GenericEventArgs e)
{
  // Inform app of new arguments
}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/single-instance-app-in-wpf-4-with-argument-passing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

