-3

I registered my application on ".mp3" Files.

My App is a Single Instance Application.

Goal: when user open a mp3 file if myApp isn't running Is start running and show the selected files count in explorer else show the app window and show the selected files count in explorer (Just Once). Then Call a function in application form that add the mylist items to listbox1.

2nd Problem: the results I get when call mylist in application form is different than the results in myfunc() why it's different?

I added commented lines thought may help!

I think my Question is clear! if it's not tell me to make it clear.

[STAThread]
    static void Main(string[] args)
    {
        if (SingleApplicationDetector.IsRunning())
        {// These Codes Runs n times!

            myfunc(); // But I want this Code Run just one time!

            return;
        }
        //myfunc();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());

        SingleApplicationDetector.Close();
    }

 public static class SingleApplicationDetector
{
    public static bool IsRunning()
    {
        string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
        var semaphoreName = @"Global\" + guid;
        try
        {
            __semaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize);

            Close();
            return true;
        }
        catch (Exception ex)
        {
            __semaphore = new Semaphore(0, 1, semaphoreName);
            return false;
        }
    }

    public static void Close()
    {
        if (__semaphore != null)
        {
            __semaphore.Close();
            __semaphore = null;
        }
    }

    private static Semaphore __semaphore;
}

 public static List<string> mylist = new List<string>();
    public static System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("ACE Music Player");
    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    public static void myfunc()
    {

        if (!File.Exists("1.txt")) // I somehow achieved my goal by using this but it does not work very well for large number of files, and of course there should be a better solution!
        {
            File.WriteAllText("1.txt", "testing");
            if (p.Length > 0)
            {
                for (int i = 0; i < p.Length; i++)
                {
                    SetForegroundWindow(p[i].MainWindowHandle);
                }
            }
           // MessageBox.Show("Running");
            {
                try
                {

                    string filename;
                    List<string> selected = new List<string>();
                    foreach (SHDocVw.InternetExplorer window in new SHDocVw.ShellWindows())
                    {
                        filename = Path.GetFileNameWithoutExtension(window.FullName).ToLower();
                        if (filename.ToLowerInvariant() == "explorer")
                        {
                            Shell32.FolderItems items = ((Shell32.IShellFolderViewDual2)window.Document).SelectedItems();
                            foreach (Shell32.FolderItem item in items)
                            {

                                if (item.Path.StartsWith(System.Environment.CurrentDirectory))
                                {
                                    selected.Add(item.Path);
                                   // mylist.Add(item.Path);
                                   //  MessageBox.Show("FilePath: " + selected[selected.Count - 1]);
                                }

                                /*
                                MessageBox.Show(Environment.GetCommandLineArgs().GetValue(1).ToString());
                                int myint = Environment.GetCommandLineArgs().GetValue(1).ToString().LastIndexOf(".");
                                MessageBox.Show(myint.ToString());
                                string str = Environment.GetCommandLineArgs().GetValue(1).ToString().Remove(myint);
                                MessageBox.Show(str);
                                if (item.Path.StartsWith(str)) 
                                {
                                    MessageBox.Show(item.Path);
                                    selected.Add(item.Path);
                                }
                                 */

                                //  selected.Add(item.Path);
                            }
                        }
                    }
                    mylist.AddRange(selected);
                   // Thread.Sleep(TimeSpan.FromMilliseconds(3000));
                    //TotalLines("");
                    // if (!File.Exists("1.txt"))
                    // {
              ////      File.WriteAllLines("1.txt", mylist.ToArray());
                  //  test();

            ////        File.WriteAllText("2.txt", File.ReadAllText("1.txt"));
            ////        File.Delete("1.txt");
                    MessageBox.Show(mylist.Count.ToString()+": "+mylist[mylist.Count - 1]);

               //     Thread.Sleep(TimeSpan.FromMilliseconds(3000));
                 //   File.WriteAllText("3.txt", "Done!");
                   // Thread.Sleep(500);
                    File.Delete("1.txt");
                }
                catch (Exception exc)
                { 
                    MessageBox.Show(exc.Message);
                }
            }
        }
    }

Update=> This is what I want to do: Player Verb

Windows SDK Download Page

I will update this post when I completely handled my problem!

but at least & finally I got the solution I was looking for. Hope this thread help others too :)

My current Problem is that sample is written in C++, and I can't understand it well till now!

and I need to mix it with my application(written in C#). If it's possible!!??

ACE
  • 379
  • 3
  • 12
  • Potential duplicate of http://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application – Martin Apr 09 '15 at 14:17
  • @MartinParkin I used mutex too! but it runs n times too – ACE Apr 09 '15 at 14:17
  • You must pass *args* to myfunc() so it knows what file was selected. And it must use inter-process communication so the 1st instance of the process can open the file. This is already [provided by the framework](http://stackoverflow.com/a/29260770/17034), don't write it yourself. – Hans Passant Apr 09 '15 at 14:23
  • @HansPassant It just pass 1 path! not all paths – ACE Apr 09 '15 at 14:24
  • @MartinParkin could you help please? – ACE Apr 09 '15 at 14:37
  • @HansPassant Could you help me please? – ACE Apr 09 '15 at 14:38

1 Answers1

1

Single app example

bool createdNew;

Mutex m = new Mutex(true, "YOURAPPNAME", out createdNew);

if (!createdNew)
{
    MessageBox.Show("already running!");
    return;
}
Steve Drake
  • 1,968
  • 2
  • 19
  • 41
  • Thanks Steve But I know how to do make application single instance only But problem is : `MessageBox.Show("already running!");` runs n times (n= Selected Files in explorer) how to force it run just once? – ACE Apr 09 '15 at 14:51
  • the return will make it quit, the MessageBox is just for illustration. – Steve Drake Apr 09 '15 at 14:54
  • Steve Assume you run make 10 shortcuts from this application then run all of them Result will be Showing messageBox 10 times! I that messageBox showed just 1 time! – ACE Apr 09 '15 at 14:56
  • The message box is not meant for production code, its to show what its doing, remove it :) – Steve Drake Apr 09 '15 at 14:58
  • Do you need to PASS the file to the RUNNING app? that's more complex, but can be done. – Steve Drake Apr 09 '15 at 14:58
  • your previous comment: I know it's just for showing but it means that that part run n times! for last comment: yeah I think that's what I'm looking for But when i use args it just show me path of 1 file! Not all selected file – ACE Apr 09 '15 at 15:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/74849/discussion-between-ace-and-steve-drake). – ACE Apr 09 '15 at 15:00
  • so, windows is only executing the program once I presume, does it pass each file as separate argument? – Steve Drake Apr 09 '15 at 15:01
  • yeah Exaxtly @Steve Drake Can you please join to chat? – ACE Apr 09 '15 at 15:03