Skip to content

Instantly share code, notes, and snippets.

@Lamparter
Last active October 10, 2024 06:22
Show Gist options
  • Save Lamparter/0c43127a6e8fc0e5f85902ff5fd1042b to your computer and use it in GitHub Desktop.
Save Lamparter/0c43127a6e8fc0e5f85902ff5fd1042b to your computer and use it in GitHub Desktop.
Create an *.exe that links to a WinAppSdk app

Resources:

Project

  • When creating, choose Windows Desktop Application

Basecode

  • Insert basecode from code sample below
  • Paste above
  //
  //  FUNCTION: MyRegisterClass()

App ID

  • Paste in place of "8ab98b2f-6dbe-4358-a752-979d011f968d_yejd587sfa94t!App"
  • Arguments are to be pasted in single-quotes in "-ArgumentList @(' ')"
  std::string command = "Start-Process 'shell:AppsFolder\\8ab98b2f-6dbe-4358-a752-979d011f968d_yejd587sfa94t!App' -ArgumentList @(' ')";

Include

  • Replace "rwinver" with Project Name
  #include "rwinver.h"

Icons

  • Rename all icons (*.ico) to "[appname].ico"

#include "framework.h"
#include "rrun.h"
#include <windows.h>
#include <string>
#include <iostream>
#include <vector>

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;                                // current instance
WCHAR szTitle[MAX_LOADSTRING];                  // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING];            // the main window class name

// Forward declarations of functions included in this code module:
ATOM                MyRegisterClass(HINSTANCE hInstance);
BOOL                InitInstance(HINSTANCE, int);
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
// Function to convert std::string to std::wstring
std::wstring StringToWString(const std::string& str) {
    int len;
    int slength = (int)str.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, NULL, 0);
    std::wstring wstr(len, 0);
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, &wstr[0], len);
    return wstr;
}

// Function to check if the application is running as admin
BOOL IsRunningAsAdmin() {
    BOOL isAdmin = FALSE;
    PSID adminGroup = NULL;
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;

    if (AllocateAndInitializeSid(&NtAuthority, 2,
        SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
        0, 0, 0, 0, 0, 0,
        &adminGroup)) {
        if (CheckTokenMembership(NULL, adminGroup, &isAdmin)) {
            isAdmin = isAdmin ? TRUE : FALSE;
        }
        FreeSid(adminGroup);
    }

    return isAdmin;
}

// Function to run a PowerShell command
void RunPowerShellCommand(const std::string& command, BOOL runAsAdmin) {
    std::string powershellCommand = command;

    if (runAsAdmin) {
        powershellCommand = "powershell.exe -Command \"" + powershellCommand + "\" -Verb RunAs";
    }
    else {
        powershellCommand = "powershell.exe -Command \"" + powershellCommand + "\"";
    }

    std::wstring wideCommand = StringToWString(powershellCommand);
    std::vector<wchar_t> commandBuffer(wideCommand.begin(), wideCommand.end());
    commandBuffer.push_back(L'\0'); // Null-terminate the string

    STARTUPINFO si = { sizeof(STARTUPINFO) };
    si.dwFlags |= STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE; // Hide the PowerShell window

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(pi));

    BOOL result = CreateProcess(
        nullptr,                     // No module name (use command line)
        commandBuffer.data(),        // Command line (wide char array)
        nullptr,                     // Process handle not inheritable
        nullptr,                     // Thread handle not inheritable
        FALSE,                       // Set handle inheritance to FALSE
        0,                           // No creation flags
        nullptr,                     // Use parent's environment block
        nullptr,                     // Use parent's starting directory 
        &si,                         // Pointer to STARTUPINFO structure
        &pi);                        // Pointer to PROCESS_INFORMATION structure

    if (result) {
        // Successfully created the process
        std::wcout << L"Process started successfully.\n";

        // Wait until the PowerShell process exits
        WaitForSingleObject(pi.hProcess, INFINITE);

        // Close process and thread handles
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }
    else {
        // Error occurred
        DWORD error = GetLastError();
        std::wcerr << L"CreateProcess failed with error code " << error << L".\n";

        // Convert error code to a message
        LPVOID msgBuffer;
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
            nullptr, error, 0, (LPWSTR)&msgBuffer, 0, nullptr);
        std::wcerr << L"Error message: " << (LPWSTR)msgBuffer << std::endl;
        LocalFree(msgBuffer);
    }
}

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);

    // Define the PowerShell command to execute
    std::string command = "Start-Process 'shell:AppsFolder\\8ab98b2f-6dbe-4358-a752-979d011f968d_yejd587sfa94t!App' -ArgumentList @(' ')";

    // Check if the application is running as admin
    BOOL isAdmin = IsRunningAsAdmin();

    // Hide the main application window
    HWND hWnd = FindWindow(NULL, L"YourWindowTitle"); // Replace with your actual window title
    if (hWnd) {
        ShowWindow(hWnd, SW_HIDE);
    }

    // Run the PowerShell command
    RunPowerShellCommand(command, isAdmin);

    // Clean up and exit
    if (hWnd) {
        ShowWindow(hWnd, SW_SHOW);
    }

    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment