【问题标题】:Why CloseMainWindow() close my command screen instead of the activate window in C#?为什么 CloseMainWindow() 关闭我的命令屏幕而不是 C# 中的激活窗口?
【发布时间】:2025-12-05 17:05:02
【问题描述】:

我想使用 C# 语音识别程序来打开和关闭文件,但是当我说关闭时,我的程序关闭了我的控制台,而不是我在启动 .wmv 文件时使用的程序,如 vlc。你能解释一下为什么会这样吗?

这是我的 SpeechRecognition 函数的代码:

private static Process lastStartedProcess;
    private static void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)//Méthode qui s'active lorsque l'ordi reconnait la phrase
    {



        if (e.Result.Text == "test")//e.Result contains the recognized text
        {
            Console.WriteLine("The test was successful");
        }

        else if (e.Result.Text == "exit")
        {
            _completed.Set(); //Calling the Set method will end the program
        }

        else if (e.Result.Text == " music")
        {
           lastStartedProcess = Process.Start(@"C:\Users\Public\Music\Sample Music\");
        }

        else if (e.Result.Text == " Pictures")
        {
           lastStartedProcess = Process.Start(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg");//En appelant music, j'affecte le process music a ma variable process

        }

        else if (e.Result.Text == " Movies")
        {
           lastStartedProcess = Process.Start(@"C:\Users\Public\Videos\Sample Videos\Wildlife.wmv");

        }

        else if (e.Result.Text == "Close")
        {
            if (lastStartedProcess != null)
            {

                lastStartedProcess.CloseMainWindow();//Ici je ferme le process qui est present dans ma variable process en appelant CloseMainWindow
                lastStartedProcess.WaitForExit();
            }

        }

    }

【问题讨论】:

  • 那么,您想从您的应用程序中关闭最后打开的程序吗?
  • 嗯,此时是的,但我想我会增强该代码,例如如果我说关闭音乐,它将关闭音乐程序而不是浏览器。但首先我想逐步处理该代码
  • 如果它只是当前答案之一中的代码,则无需更新问题中的代码。您现在已经使您的问题没有任何意义,因为显示的代码不会关闭您的应用程序,这就是问题标题和您的叙述所说的发生的情况。
  • 哦,是的,你是对的,我没有注意这些宝贵的细节。对不起。那么我该如何解决这个问题?如果我需要更新我的代码来解释我自己,我将不得不输入一个新的答案,还是我必须用 500 个字符来解释自己?

标签: c# speech-recognition


【解决方案1】:

Process.GetCurrentProcess() 将获取您的语音识别过程。您需要引用从 Process.Start 调用返回的 Process 实例。

【讨论】: