0

現在、ゲームのランチャーをプログラムしようとしています。私の問題は、この方法でゲームを起動した場合です。

System.Diagnostics.Process.Start(@"F:\Freak Mind Games\Projects 2013\JustShoot\game.bat");

未処理の例外が発生するか、エラーが見つかりませんでした。

しかし、私がこのようにすると:

System.Diagnostics.Process.Start(@"game.bat");

できます。問題はどこにありますか?

4

1 に答える 1

3

バッチ ファイルは、プログラム ランチャーと同じディレクトリにあると想定しています。その場所を自動的に決定します。

string executableDir = Path.GetDirectoryName(Application.ExecutablePath);
Process.Start(Path.Combine(executableDir, "game.bat"));

どこ

  • Application.ExecutablePath実行可能ファイルのパスです F:\Freak Mind Games\Projects 2013\JustShoot\justshoot.exe

  • Path.GetDirectoryName(...)そのディレクトリ部分を取得し F:\Freak Mind Games\Projects 2013\JustShootます。

  • Path.Combine(executableDir, "game.bat")game.batディレクトリをと結合します。F:\Freak Mind Games\Projects 2013\JustShoot\game.bat


また、Visual Studio から起動した場合、実行可能パスは"...\bin\Debug"または"...\bin\Release". したがって、バッチ ファイルがプロジェクト ディレクトリにある場合は、これらの部分をパスから削除することをお勧めします。

const string DebugDir = @"\bin\Debug";
const string ReleaseDir = @"\bin\Release";

string executableDir = Path.GetDirectoryName(Application.ExecutablePath);
if (executableDir.EndsWith(DebugDir)) {
    executableDir =
        executableDir.Substring(0, executableDir.Length - DebugDir.Length);
} else if (executableDir.EndsWith(ReleaseDir)) {
    executableDir =
        executableDir.Substring(0, executableDir.Length - ReleaseDir.Length);
}
Process.Start(Path.Combine(executableDir, "game.bat"));

アップデート

ディレクトリをハードコードするのは得策ではありません。起動するゲームのパスを、ゲーム ランチャーと同じディレクトリ内のテキスト ファイルに配置します (例: "launch.txt")。各行には、ゲームの名前とそのパスで起動できるゲームが含まれます。このような:

フリーク マインド ゲーム = F:\フリーク マインド ゲーム\プロジェクト 2013\JustShoot\game.bat
マインクラフト = C:\Programs\Minecraft\minecraft.exe

フォームでディレクトリを変数として定義します。

private Dictionary<string,string> _games;

これらのゲームのリストを次のように取得します。

string executableDir = Path.GetDirectoryName(Application.ExecutablePath);
string launchFile = Path.Combine(executableDir, "launch.txt"));

string[] lines = File.ReadAllLines(launchFile);

// Fill the dictionary with the game name as key and the path as value.
_games = lines
    .Where(l => l.Contains("="))
    .Select(l => l.Split('='))
    .ToDictionary(s => s[0].Trim(), s => s[1].Trim());

次に、ゲーム名を次のように表示しますListBox

listBox1.AddRange(
     _games.Keys
        .OrderBy(k => k)
        .ToArray()
);

最後に、選択したゲームを起動します

string gamePath = _games[listBox1.SelectedItem];
var processStartInfo = new ProcessStartInfo(gamePath);
processStartInfo.WorkingDirectory = Path.GetDirectoryName(gamePath);
Process.Start(processStartInfo); 
于 2013-04-16T19:25:58.343 に答える