简体   繁体   English

在Windows启动时由C ++应用程序启动JAR文件将无法运行

[英]JAR file won't run when it's been started by C++ app on Windows startup

I have a JAR file, which I want to run on system startup (OS=Windows). 我有一个JAR文件,我想在系统启动时运行它(OS = Windows)。 To achieve the program to be run on system start, I've done two things: 为了使程序在系统启动时运行,我做了两件事:

  • I made an executable in C++, which will trigger the JAR file to be started. 我用C ++编写了一个可执行文件,它将触发JAR文件的启动。
  • Created a registry key named MyApp (name doesn't actually matter) in HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Run with as value the path to the executable. HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Run创建了一个名为MyApp的注册表项(名称实际上并不重要),并将可执行文件的路径作为值。

The code of the executable is as follows: 可执行文件的代码如下:

BOOL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR commandLine, int nCmdShow) {

    ShowWindow(GetConsoleWindow(), SW_HIDE);

    // First display a box with text 'Hello!'
    stringstream msg; msg << "Hello!";
    MessageBox(NULL, msg.str().c_str(), "", MB_OK);

    // getJavaHome is a function
    stringstream javadir; javadir << getJavaHome() << "\\bin\\java.exe";
    stringstream params; params << " -jar jarfile.jar";

    STARTUPINFO info = { sizeof (info) };
    PROCESS_INFORMATION processInfo;

    char* path = stringToCharArray(javadir.str().c_str());
    char* args = stringToCharArray(params.str().c_str());

    if (CreateProcess(path, args, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &info, &processInfo)) {
        ::WaitForSingleObject(processInfo.hProcess, INFINITE);
        CloseHandle(processInfo.hProcess);
        CloseHandle(processInfo.hThread);
    }
    return 0;
}

Notice that, as you can see, this program will, before starting the JAR file, output a message box saying "Hello!" 请注意,如您所见,该程序将在启动JAR文件之前输出一个消息框,显示“ Hello!”。

Now here's the strange thing: 现在这是奇怪的事情:

  • When I run the executable by double-clicking on it, it will display the messagebox and then it'll start the JAR file. 当我通过双击运行可执行文件时,它将显示消息框,然后将启动JAR文件。
  • But when the system starts up and the application is triggered to be started, it will display Hello , but it won't start the JAR file. 但是,当系统启动和应用程序被触发启动,它显示Hello,但它不会启动JAR文件。

How on earth come? 到底是怎么来的? Annnd... How to solve it? Ann ...如何解决?

I suppose it's a problem with the working directory—eventually it is completely different when autostarted. 我想这是工作目录的问题-最终在自动启动时完全不同。 So you should either pass the proper working directory (can't tell if this can be done with CreateProcess() ); 因此,您应该传递正确的工作目录(无法告诉您是否可以使用CreateProcess()完成此操作); or give a fixed absolute path to your JAR file. 或为您的JAR文件提供固定的绝对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM