Search code examples
c#executablelauncherlaunching-application

C# Windows Application - Linking a button to start a game


I believe I have been taking the right approach to this so far, but I would like to have a button start a video game on my computer.

So far, I have a button linking to a process:

void button2_Click(object sender, EventArgs e)
{
    process1.Start();
}

this.process1.EnableRaisingEvents = true;
this.process1.StartInfo.Domain = "";
this.process1.StartInfo.FileName = "MBO\\marbleblast.exe";
this.process1.StartInfo.LoadUserProfile = false;
this.process1.StartInfo.Password = null;
this.process1.StartInfo.StandardErrorEncoding = null;
this.process1.StartInfo.StandardOutputEncoding = null;
this.process1.StartInfo.UserName = "";
this.process1.SynchronizingObject = this;
this.process1.Exited += new System.EventHandler(this.Process1Exited);

So, where-ever I place the EXE (the one I'm coding), it will launch the "marbleblast.exe" under the subfolder MBO relative to it's location.

It seems to be working and trying to launch the game, however, it says it cannot load files that are there. I tested the game without my launcher, and it worked. I believe it's trying to run the EXE, but not letting it use the other files inside of it's folder.

I'll give more details if needed.

How can I get the game to run normally?


Solution

  • this.process1.StartInfo.WorkingDirectory= "MBO\";

    There's sloppy programming in the game, it relies on the Environment.CurrentDirectory being set right. Which by default is the same directory as where the EXE is located. The upvoted answer repeats the mistake though. To make that statement actually fix the problem, you now rely on your CurrentDirectory being set right. If it is not set where you think it is then it still won't work.

    The problem with the program's current directory is that it can be changed by software that you don't control. The classic example is OpenFileDialog with the RestoreDirectory property set to the default value of false. Etcetera.

    Always program defensively and pass the full path name of files and directories. Like c:\mumble\foo.ext. To get that going, start with Assembly.GetEntryAssembly().Location, that's the path to your EXE. Then use the System.IO.Path class to generate path names from that. The correct always-works code is:

    using System.IO;
    using System.Reflection;
    ...
            string myDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string gameDir = Path.Combine(myDir, "MBO");
            string gameExe = Path.Combine(gameDir, "marbleblast.exe");
            process1.StartInfo.FileName = gameExe;
            process1.StartInfo.WorkingDirectory = gameDir;
            process1.SynchronizingObject = this;
            process1.EnableRaisingEvents = true;
            process1.Exited += new EventHandler(Process1Exited);