Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中只运行一次主程序中的特定部分代码?_C#_Single Instance - Fatal编程技术网

如何在C#中只运行一次主程序中的特定部分代码?

如何在C#中只运行一次主程序中的特定部分代码?,c#,single-instance,C#,Single Instance,我在“.mp3”文件上注册了我的应用程序 我的应用程序是一个单实例应用程序 目标:当用户打开mp3文件时,如果myApp未运行,则开始运行,并在资源管理器中显示选定的文件数,否则显示应用程序窗口,并在资源管理器中显示选定的文件数(仅一次)。然后在应用程序窗体中调用一个函数,将mylist项添加到listbox1 第二个问题:我在申请表中调用mylist时得到的结果与myfunc()中的结果不同,为什么不同 我添加了评论行,认为可能会有所帮助 我想我的问题很清楚!如果不是,告诉我说清楚 [STAT

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

我的应用程序是一个单实例应用程序

目标:当用户打开mp3文件时,如果myApp未运行,则开始运行,并在资源管理器中显示选定的文件数,否则显示应用程序窗口,并在资源管理器中显示选定的文件数(仅一次)。然后在应用程序窗体中调用一个函数,将
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();
    }


publicstaticlist mylist=newlist();
public static System.Diagnostics.Process[]p=System.Diagnostics.Process.GetProcessesByName(“ACE音乐播放器”);
[DllImport(“user32.dll”)]
静态外部bool setforegroundindow(IntPtr hWnd);
公共静态void myfunc()
{
如果(!File.Exists(“1.txt”)//我通过使用它不知何故实现了我的目标,但它对于大量文件来说效果不是很好,当然应该有更好的解决方案!
{
writealText(“1.txt”,“testing”);
如果(p.Length>0)
{
对于(int i=0;i
更新=> 这就是我想做的:

当我完全解决我的问题时,我会更新这个帖子

但至少&最终我找到了我想要的解决方案。 希望这个帖子也能帮助别人:)

我目前的问题是用C++编写的样板,到现在我还不能很好的理解! 我需要将它与我的应用程序(用C#编写)混合使用。如果可能的话!!??

单个应用程序示例

bool createdNew;

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

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

@MartinParkin的潜在副本我也使用了互斥!但它运行了n次,您必须将参数传递给myfunc()所以它知道选择了什么文件。它必须使用进程间通信,以便进程的第一个实例可以打开该文件。这已经存在,不要自己编写。@hanpassant它只通过一个路径!不是全部paths@MartinParkin你们能帮忙吗?谢谢Steve,但我知道如何使应用程序只成为一个实例,但问题是:
MessageBox.Show(“已在运行!”);
运行n次(n=资源管理器中选定的文件)如何强制它只运行一次?返回将使它退出,MessageBox仅用于说明。Steve假设您从此应用程序运行make 10快捷方式,然后运行所有这些快捷方式,结果将显示MessageBox 10次!我认为MessageBox只显示了1次!MessageBox不是用于生产代码的,它是为了显示它在做什么,请删除it:)是否需要将文件传递到正在运行的应用程序?这更复杂,但可以完成。
 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);
                }
            }
        }
    }
bool createdNew;

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

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