Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save justaguywhocodes/f6b8b3acbbc0ee5108e57f032be9c95e to your computer and use it in GitHub Desktop.
Save justaguywhocodes/f6b8b3acbbc0ee5108e57f032be9c95e to your computer and use it in GitHub Desktop.
Process start
Here's a simple C program that launches calc.exe using the Windows API:
```c
#include <windows.h>
int main() {
// Use ShellExecute to launch calculator
HINSTANCE result = ShellExecuteA(NULL, "open", "calc.exe", NULL, NULL, SW_SHOW);
// Check if the execution was successful
if ((int)result <= 32) {
// Error occurred
return 1;
}
return 0;
}
```
This code:
1. Includes the necessary Windows header
2. Uses `ShellExecuteA` (ANSI version) to launch calc.exe
3. The parameters are:
- NULL: No window handle needed
- "open": Operation to perform
- "calc.exe": File to execute
- NULL: No parameters
- NULL: Default directory
- SW_SHOW: Shows the window normally
4. Checks if the execution was successful (returns > 32 on success)
5. Returns appropriate exit code
To compile this with something like GCC (MinGW):
```
gcc -o calc_launcher calc_launcher.c
```
Alternatively, here's a version using `CreateProcess` which gives more control:
```c
#include <windows.h>
int main() {
STARTUPINFOA si = {0};
PROCESS_INFORMATION pi = {0};
// Initialize startup info
si.cb = sizeof(si);
// Create the process
BOOL success = CreateProcessA(
"C:\\Windows\\System32\\calc.exe", // Full path to calculator
NULL, // No command line arguments
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Don't inherit handles
0, // No creation flags
NULL, // Use parent's environment
NULL, // Use parent's directory
&si, // Startup info
&pi // Process info
);
if (!success) {
return 1;
}
// Clean up process and thread handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}
```
Both versions will work on Windows systems. The `ShellExecuteA` version is simpler but less configurable, while the `CreateProcessA` version gives you more control over the process creation but requires more setup.
Note: The actual path to calc.exe might vary depending on your Windows installation (though ShellExecute will usually find it in the system directory automatically).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment