C++ java 啓動器

#include <Windows.h>
#include <stdlib.h>
#include <string>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){
    // 設置環境變量 java_home
    std::wstring java_home = L"D:\\Tools\\jdk\\Java_11_win";
    _wputenv_s(L"java_home", java_home.c_str());

    // 設置環境變量 classpath
    //std::wstring classpath = L".;C:\\myapp\\lib\\*";
    //std::wstring env_classpath = L"classpath=" + classpath;
    //_wputenv_s(L"classpath", env_classpath.c_str());

    std::wstring java_exe = java_home+L"\\bin\\java.exe";
    std::wstring jar = L"abc.jar";
    std::wstring command = java_exe + L" -jar " + jar;


    STARTUPINFOW si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    CreateProcessW(NULL, (wchar_t*)command.c_str(), NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi);

    return 0;
}

//int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){
//原因:VS工程屬性配置問題,【鏈接器】->【系統】->【子系統】設置成了控制檯
//解決方案:【連接器】->【系統】->【子系統】修改爲窗口
//右擊資源文件->添加->資源->Icon->導入-> logo.ico


using System;
using System.IO;
using System.Runtime.InteropServices;

namespace 啓動器
{
    internal class Program
    {
        public const uint DETACHED_PROCESS = 0x00000008;
        static void Main(string[] args)
        {
            var java = @"D:\Tools\bin\java.exe";
            var jar = @"D:\Tools\a.jar";
            var command = $"{java} -jar {jar}";
            var dir = Path.GetDirectoryName(jar);
            var flag = DETACHED_PROCESS;
            STARTUPINFO startInfo = new STARTUPINFO();
            PROCESS_INFORMATION procInfo = new PROCESS_INFORMATION();
            CreateProcess(null, command, IntPtr.Zero, IntPtr.Zero, false, flag, IntPtr.Zero, dir, ref startInfo, out procInfo);

        }
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
        static extern bool CreateProcess(string lpApplicationName, string lpCommandLine,
            IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles,
            uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory,
            [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION
                lpProcessInformation);
        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public int dwProcessID;
            public int dwThreadID;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public struct STARTUPINFO
        {
            public uint cb;
            public string lpReserved;
            public string lpDesktop;
            public string lpTitle;
            public uint dwX;
            public uint dwY;
            public uint dwXSize;
            public uint dwYSize;
            public uint dwXCountChars;
            public uint dwYCountChars;
            public uint dwFillAttribute;
            public uint dwFlags;
            public ushort wShowWindow;
            public ushort cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }
    }
}

            using AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
            using AutoResetEvent errorWaitHandle = new AutoResetEvent(false);
            using Process process = new Process();
            // Configure the process using the StartInfo properties.
            process.StartInfo.FileName = "D:\\Tools\\jre\\bin\\java.exe";
            process.StartInfo.Arguments = "-jar D:\\Tools\\abc.jar";
            process.StartInfo.WorkingDirectory = Application.StartupPath;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardOutput = true;

            // Need to provide encoding info, or output/error strings we got will be wrong.
            process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
            process.StartInfo.StandardErrorEncoding = Encoding.Unicode;

            process.StartInfo.CreateNoWindow = true;

            StringBuilder output = new StringBuilder();
            StringBuilder error = new StringBuilder();

            process.OutputDataReceived += (sender, e) =>
            {
                if (e.Data == null)
                {
                    outputWaitHandle.Set();
                }
                else
                {
                    output.AppendLine(e.Data);
                }
            };
            process.ErrorDataReceived += (sender, e) =>
            {
                if (e.Data == null)
                {
                    errorWaitHandle.Set();
                }
                else
                {
                    error.AppendLine(e.Data);
                }
            };
            try
            {
                process.Start();

                process.BeginErrorReadLine();
                process.BeginOutputReadLine();

                Application.Exit();
                Environment.Exit(0);
                process.WaitForExit();
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                // log the arguments
                throw new Exception(process.StartInfo.Arguments, e);
            }
            string stderr = error.ToString();
            string stdout = output.ToString();

            int exitCode = process.ExitCode;
            if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
            {
                throw new Exception(stderr);
            }

            Console.WriteLine(stdout);
            Console.WriteLine(stderr);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章