C++ java 启动器

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

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){
    std::filesystem::path currentDir = std::filesystem::current_path();
    // 设置环境变量 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;

    bool fileExists = std::filesystem::exists(currentDir / jar );
    if (fileExists)
    {
        STARTUPINFOW si = { sizeof(si) };
        PROCESS_INFORMATION pi;
        CreateProcessW(NULL, (wchar_t*)command.c_str(), NULL, NULL, FALSE, DETACHED_PROCESS, NULL, currentDir.c_str(), &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);
posted @ 2023-06-04 15:11  月渊  阅读(19)  评论(0编辑  收藏  举报