Author Topic: Simple CreateProcess Win32 MSDN Example  (Read 3092 times)

0 Members and 1 Guest are viewing this topic.

Offline SpriggsySpriggs

  • Forum Resident
  • Posts: 1145
  • Larger than life
    • View Profile
    • GitHub
Simple CreateProcess Win32 MSDN Example
« on: May 11, 2021, 04:39:09 pm »
Based on the MSDN page for Creating Processes, here is a super simple way to demonstrate starting another application from QB64 using the Win32 API function set. The below code uses all functions used in the MSDN example. It is designed to be compiled as a console application and ran from CMD or PowerShell. You will pass it the name or full path of another executable to run as the argument.

Code: QB64: [Select]
  1.  
  2. Type STARTUPINFO
  3.     As Long cb
  4.     $If 64BIT Then
  5.         As Long padding
  6.     $End If
  7.     As _Offset lpReserved, lpDesktop, lpTitle
  8.     As Long dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags
  9.     As Integer wShowWindow, cbReserved2
  10.     $If 64BIT Then
  11.         As Long padding2
  12.     $End If
  13.     As _Offset lpReserved2, hStdInput, hStdOutput, hStdError
  14.  
  15. Type PROCESS_INFORMATION
  16.     As _Offset hProcess, hThread
  17.     As Long dwProcessId
  18.     $If 64BIT Then
  19.         As Long padding
  20.     $End If
  21.  
  22. Const INFINITE = 4294967295
  23.  
  24.     Function CreateProcess%% Alias "CreateProcessA" (ByVal lpApplicationName As _Offset, lpCommandLine As String, Byval lpProcessAttributes As _Offset, Byval lpThreadAttributes As _Offset, Byval bInheritHandles As Integer, Byval dwCreationFlags As Long, Byval lpEnvironment As _Offset, Byval lpCurrentDirectory As _Offset, Byval lpStartupInfor As _Offset, Byval lpProcessInformation As _Offset)
  25.     Sub CloseHandle (ByVal hObject As _Offset)
  26.     Sub WaitForSingleObject (ByVal hHandle As _Offset, Byval dwMilliseconds As Long)
  27.     Sub printf (template As String, arg As String)
  28.     Sub printf2 Alias "printf" (template As String, Byval dwArg As Long)
  29.     Function GetLastError& ()
  30.     Sub ZeroMemory Alias "SecureZeroMemory" (ByVal Destination As _Offset, Byval Length As _Offset)
  31.  
  32. Dim As STARTUPINFO si
  33. Dim As PROCESS_INFORMATION pi
  34.  
  35. ZeroMemory _Offset(si), Len(si)
  36. ZeroMemory _Offset(pi), Len(pi)
  37.  
  38. si.cb = Len(si)
  39.  
  40.     printf "Usage: %s [cmdline]" + Chr$(10) + Chr$(0), Command$(0)
  41.     System
  42.  
  43. If CreateProcess(0, Command$(1) + Chr$(0), 0, 0, 0, 0, 0, 0, _Offset(si), _Offset(pi)) = 0 Then
  44.     printf2 "CreateProcess failed (%d)." + Chr$(10) + Chr$(0), GetLastError
  45.     System
  46.  
  47. WaitForSingleObject pi.hProcess, INFINITE
  48.  
  49. CloseHandle pi.hProcess
  50. CloseHandle pi.hThread
Shuwatch!