如何在C#中只运行一次Program Main中的特定部分代码?

时间:2015-04-09 14:09:51

标签: c# single-instance

我在“.mp3”文件上注册了我的应用程序。

我的应用程序是单实例应用程序。

目标:当用户未运行时打开mp3文件当用户开始运行并在资源管理器中显示所选文件数时,显示应用程序窗口并在资源管理器中显示所选文件计数(Just Once)。然后在应用程序表单中调用一个函数,将mylist项添加到listbox1

第二个问题:我在申请表中拨打mylist时得到的结果与myfunc()中的结果不同,为什么会有所不同?

我添加了评论线,认为可能有所帮助!

我认为我的问题很明确!如果它没有告诉我说清楚。

[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);
                }
            }
        }
    }

更新=&GT; 这就是我想要做的: Player Verb

Windows SDK Download Page

当我完全处理我的问题时,我会更新这篇文章!

但至少&amp;最后我得到了我正在寻找的解决方案。 希望这个帖子也能帮助别人:)

我目前的问题是样本是用C ++编写的,直到现在我都无法理解!

我需要将它与我的应用程序混合(用C#编写)。如果有可能!! ??

1 个答案:

答案 0 :(得分:1)

单个应用示例

bool createdNew;

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

if (!createdNew)
{
    MessageBox.Show("already running!");
    return;
}