【问题标题】:How to not lose focus when running a c# process?运行 c# 进程时如何不失去焦点?
【发布时间】:2015-07-26 11:16:20
【问题描述】:

我正在尝试从控制台通过 c# 中的process.diagnostics 在新进程中运行 mp3 文件;但是,控制台会做其他事情,所以我不想失去焦点。我查看了论坛,最终我认为您需要使用两个属性来执行此操作:

StartInfo.CreateNoWindow = true; // has to be set to true
info.WindowStyle = ProcessWindowStyle.Hidden; // or minimized.

尽管如此,当我尝试以下操作时:

        ProcessStartInfo info = new ProcessStartInfo(@"path to mp3 file here");
        info.CreateNoWindow = true;
        info.WindowStyle = ProcessWindowStyle.Hidden;
        Process.Start(info);

我仍然失去焦点,带有 mp3 文件的 Windows 媒体播放器打开并从控制台获取焦点。

我做错了什么?

【问题讨论】:

    标签: c# process diagnostics


    【解决方案1】:

    问题是通过诊断创建进程不一致 - 它可能会也可能不会返回 hProcess 句柄,因此不会受到对进程的操作的影响,因为它可以使用现有进程进行操作 - 并且你拿回来的句柄是没有意义的。

    然而,这还没有结束。我找到了一种更好的方法来处理从控制台播放的文件。 System.Media.AudioPlayer 允许以非常一致、可预测的方式处理 .wav 文件。我用this useful tool转换了我的mp3,现在代码很简单:

    public SoundPlayer playOpeningTheme()
    {
            SoundPlayer myPlayer = new SoundPlayer(@"Path here.wav");
            myPlayer.PlayLooping();
            return myPlayer;
    }
    

    之后使用 soundplayer 对象来影响播放非常简单,例如:

            SoundPlayer myPlayer = playOpeningTheme();
            // do stuff while the music is playing
            // and then easily, without all the process mess, you can simply:
            myPlayer.Stop();
            myPlayer.Dispose();
            // and keep on from here (: 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多