How can I make a Click-once deployed app run at startup?

后端 未结 11 1756

How can I make a Click-once deployed app run a startup?

The best option I found by searching was to set the Publisher on the app to Startup, so the Start menu shortc

11条回答
  •  天命终不由人
    2020-12-04 22:38

    After reading all the comments on this thread and the johnnycoder blog post mentioned above, I came up with a solution that:

    1. Adds your ClickOnce app to the Startup folder
    2. Removes the Startup item automatically when the ClickOnce app is uninstalled (after a reboot or log out/log in)
    3. Was tested and works on Windows XP, Windows 7, Windows Server 2000/2003, Windows 8

    My Solution

    Basically, your app will be writing a .bat file to the Startup folder that launches the ClickOnce app for you. The .bat file is smart enough to detect if the app has been uninstalled and will delete itself if the ClickOnce app cannot be found.

    Step 1

    Get the batch file working. Replace PUBLISHER_NAME and APPLICATION_NAME with the right values. You can find them by installing your ClickOnce app, then following the path to it on your file system:

    @echo off
    
    IF EXIST "%appdata%\Microsoft\Windows\Start Menu\Programs\PUBLISHER_NAME\APPLICATION_NAME.appref-ms" (
    "%appdata%\Microsoft\Windows\Start Menu\Programs\PUBLISHER_NAME\APPLICATION_NAME.appref-ms"
    ) ELSE (start /b "" cmd /c del "%~f0"&exit /b)
    

    The batch file will check if your ClickOnce app is installed (by seeing if the appref-ms file exists) and launch it if so. Otherwise, the batch file deletes itself, via a method outlined here.

    Now that you have the batch file, test it out. Drop it in your Startup folder to make sure it launches your app on login.

    Step 2

    Now, in the code for your app, you need to write this batch file to the Startup folder. Here is an example using the batch file above in C# (note that there is some escaping, and environment variable voodoo happening):

    string[] mystrings = new string[] { @"@echo off
    
    IF EXIST ""%appdata%\Microsoft\Windows\Start Menu\Programs\PUBLISHER_NAME\APPLICATION_NAME.appref-ms"" (
    ""%appdata%\Microsoft\Windows\Start Menu\Programs\PUBLISHER_NAME\APPLICATION_NAME.appref-ms""
    ) ELSE (start /b """" cmd /c del ""%~f0""&exit /b)"};
    
    string fullPath = "%appdata%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\StartMyClickOnceApp.bat";
    
    //Expands the %appdata% path and writes the file to the Startup folder
    System.IO.File.WriteAllLines(Environment.ExpandEnvironmentVariables(fullPath), mystrings);
    

    There you have it. Comments / improvements welcomed.

    EDIT: Fixed quotes in step 2

提交回复
热议问题