Run .jar through Windows shortcut passing arguments

前端 未结 1 1527
余生分开走
余生分开走 2020-12-19 14:58

Is it possible run .jar through Windows shortcut (.lnk) passing arguments?

相关标签:
1条回答
  • 2020-12-19 15:33

    In Java 7, yes. You can point the shortcut to c:\windows\system32\java.exe or javaw.exe as appropriate and include the same arguments you would use on the command line.

    In a clean Java 8 installation, not easily. Unfortunately Java 8 no longer puts copies java.exe and javaw.exe into the system folder, but instead puts symbolic links in a ProgramData folder. Windows doesn't like shortcuts to symbolic links; sometimes they work, sometimes they don't. (Even the same shortcut might work for some user accounts but not for others.)

    (It seems that if you install Java 8 over top of Java 7 it retains the old behaviour, but I haven't investigated this thoroughly yet.)

    This simple launcher may be useful; you can create one or more shortcuts to it with the same command line parameters you would have used in the shortcut to javaw.exe.

    #include <Windows.h>
    
    void NoCRTMain(void)
    {
        wchar_t * cmdline = GetCommandLineW();
        STARTUPINFO si;
        PROCESS_INFORMATION pi;
    
        GetStartupInfo(&si);
    
        if (!CreateProcess(L"C:\\ProgramData\\Oracle\\Java\\javapath\\javaw.exe", cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
        {
            MessageBox(NULL, L"Unable to launch Java.", L"runjava.exe", MB_OK);
        }
    
        ExitProcess(0);
    }
    

    To compile in Visual Studio, you will need to change some project settings:

    • Buffer Security Check to No in C/C++ Code Generation
    • Ignore All Default Libraries to Yes in Linker Input
    • Entry Point to NoCRTMain in Linker Advanced
    • Randomized Base Address to No in Linker Advanced (see commentary here)

    (Or you can change the main function from NoCRTMain to WinMain, but then you need to install the C runtime or link it statically.)


    Additional: in Windows 10, if you have two Start Menu shortcuts pointing to the same executable, only one of them will be visible in the Start Menu. So in this case you need to have multiple copies of the launcher, one for each shortcut.

    0 讨论(0)
提交回复
热议问题