Execute JAVA program from Windows 7 WPF application
Question: I need to execute an external JAVA program from my Windows 7 WPF application during the installation and configuration phase. I use Visual Studio 2008 and CSharp. What to do?
Your JAVA app is definiately an external program and assumes you have installed Java Runtime Environment to execute it. Check out your configuration and try to run your Java application from the Command Prompt. Use the same command line you want to execute from the Windows program.
With .NET framework things have become simple to go ahead. The System.Diagnostics namespace exposes a Process class that you can use to launch external programs. At the simplest level, you can launch a new process with the shared Process.Start method, passing it either the name of an executable file or a filename with an extension associated with an executable application.
In your WPF project use ProcessStartInfo together with the Process component to execute commands: See .NET Framework Class Library for example
Launching an application from WPF Window using Process Class
// This code assumes the JRE is installed and the process we are starting
// will terminate itself.
// Given that it is started without a window so you cannot terminate it
// on the desktop, it must terminate itself.
// When you have to some way monitor the launched process and find out
// when it exits or sometimes, whether it's still running, depending on your
// application, you may need to approach that problem.
// See the link under the sample code.
public void RunMyJavaApp(string javaCmdLine)
{
string commandLine = "java -jar "C:\\My Projects\\Java Projects\\test\\test.jar" ";
// cmd.exe is in the C:\WINDOWS\system32\ folder
ProcessStartInfo PSI = new ProcessStartInfo("cmd.exe");
PSI.RedirectStandardInput = true;
PSI.RedirectStandardOutput = true;
PSI.RedirectStandardError = true;
PSI.UseShellExecute = false;
Process p = Process.Start(PSI);
System.IO.StreamWriter SW = p.StandardInput;
System.IO.StreamReader SR = p.StandardOutput;
SW.WriteLine(commandLine + javaCmdLine);
SW.Close();
}
.......
// Call your method with your java parameters:
RunMyJavaApp("-i="test.txt" -o="test_output.txt"");