简体   繁体   中英

How to not lose focus when running a c# process?

I'm trying to run a mp3 file in a new process via process.diagnostics in c# from the console; However, the console does other stuff, so I don't want to lose focus. I looked around the forums, and eventually I figured you need to use two properties to do this:

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

Despite that, when I try the following:

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

I still lose focus, and a windows media player with the mp3 file opens and takes the focus from the console.

What am I doing wrong?

The problem was creating a process via diagnostics is not consistent - It may and may not return a hProcess handle back, and thus could not be affected by manipulations on the process, because it could use an existing process for the operation - and the handle you get back is meaningless.

However, that was not the end. I found a much better way to handle playing files from the console. System.Media.AudioPlayer Allows a very consistant, predictable way to handle with .wav files. I converted my mp3s with this useful tool , and now the code is as simple as:

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

Using the soundplayer object afterward to affect the playing is pretty simple, for example:

        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 (: 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM