Spiralwise
Spiralwise

Reputation: 348

Win32 application doesn't run on startup

I have created a C++ Win32 application in Visual Studio 2015. My goal is to make it run at startup. I added a new entry in registry (HKCU\Software\Microsoft\Windows\CurrentVersion\Run). For an unknown reason, it doesn't work.

However it appears correctly in the Task Manager at the Startup tab but not in the Process tab which means it doesn't run at all. I tried to wrap it in a bat file. The bat runs but the application seems to fail at launch (or totally ignored, I can't tell exactly). If I launch manually from Program Files directory, it runs normally.

It's an old Visual project from a friend and it was converted in the current Visual (2015). If I create a new project from scratch, it works. But there is no reason for such behavior.

Final thought - I successully resolved my issue. My program was unable to find the SQLite file because any programs launch by Windows on startup use "c:\Windows\System32" as current directory. I just applied Marko Popovic's solution. It was just a simple current directory problem.

PS - Marko Popovic's solution is good but @IInspectable warns about incoming bugs that could occured with this method. He recommands to only use fully qualified pathname without changing dir.

Upvotes: 1

Views: 1647

Answers (1)

Marko Popovic
Marko Popovic

Reputation: 4153

When the application is started using the "Run" key, its working directory is not the one where its image file (*.exe) resides. You can change this by calling Win32 function SetCurrentDirectory at the very beginning of your main function. Here is a skeleton of a solution:

// Use GetModuleFileName to retrieve path of the executable file
TCHAR pszPathToSelf[MAX_PATH];
DWORD dwPathLength = GetModuleFileName(NULL, pszPathToSelf, MAX_PATH);
if(dwPathLength > 0)
{
    // Code that extracts directory path from pszPathToSelf and places it into variable pszNewWorkingDirectory of type TCHAR
    ...

    BOOL bSuccess = SetCurrentDirectory(pszNewWorkingDirectory);
    if(0 == bSuccess)
    {
    // SetCurrentDirectory failed for some reason, handle how you see fit
    ....
    }
} 

This way, your function will change its working directory and load the necessary DLL.

EDIT: As user IInspectable pointed out, the above approach will not work in the default case, but only in some special ones. A better approach would be to register your application under App Paths registry key. If your application is named my_app.exe, create the following registry key: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\my_app.exe and then create a REG_SZ value namedPath, which will contain the path to directory that holds my_app.exe.

For more details, refer to the following MSDN page:

https://msdn.microsoft.com/en-us/library/windows/desktop/ee872121%28v=vs.85%29.aspx

Sorry for the initial mistake!

Upvotes: 3

Related Questions