runifnot.xsh

Execute program if it is not running already

<?xml version="1.0" encoding="utf-8"?>
<xsharper xmlns="http://www.xsharper.com/schemas/1.0">
    <versionInfo title="RunIfNot" value="Run a program if a certain top-level window does not exist." Version="0.1.0.0" Copyright="(C) 2009 DeltaX Inc." />
    <usage options="ifNoArguments | default" />
    <param name="process-name" required="true">Process name, w/o .exe. For example, 'explorer'</param>
    <param name="title-wildcard" required="true">Wildcard to match window title (if starts with ^ - treat as regex)</param>
    <param name="command-line" required="true" count="multiple" last="true">Command line to execute if the window is not found</param>
    <header>
        using System.Runtime.InteropServices;
        using System.Diagnostics;
        
        static class Native {
            [DllImport("user32.dll", SetLastError = true)]
            public static extern bool BringWindowToTop(IntPtr hWnd);

            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool SetForegroundWindow(IntPtr hWnd);
        }
    </header>
    <code>
        XS.StringFilter sf=new XS.StringFilter(c.GetStr("title-wildcard"));
        foreach (Process p in Process.GetProcessesByName(c.GetStr("process-name")))
        {
            if (sf.IsMatch(p.MainWindowTitle))
            {
                Native.SetForegroundWindow(p.MainWindowHandle);
                Native.BringWindowToTop(p.MainWindowHandle);
                return 0;
            }
            
        }
    </code>
    <shell mode="shellExecute" wait="false"><param>${command-line}</param></shell>
</xsharper>