Introduction
I wanted to find a simple way of running a script (e.g. Perl, PHP, etc.) on a webserver but it needed to be asynchronous as I didn't want the application to hang while waiting for the webserver's response. I didn't need to read any output from the script so all the solutions I could find were overly complicated for my needs.
Theory
- Use
INTERNET_FLAG_ASYNC
to open the session - Set a status callback using
InternetSetStatusCallback
- Open the connection using
InternetOpenUrl
- Read the handle when the callback function receives
INTERNET_STATUS_HANDLE_CREATED
- Free up everything when the call has finished and the callback function receives
INTERNET_STATUS_REQUEST_COMPLETE
Using the Code
The complete code is:
HINTERNET hInternetSession = NULL;
HINTERNET hURL = NULL;
typedef struct
{
HWND hWindow; HINTERNET hResource; } REQUEST_CONTEXT;
REQUEST_CONTEXT request_context;
void __stdcall InternetCallbackFunction(HINTERNET hInternet,
DWORD dwContext,
DWORD dwInternetStatus,
LPVOID lpvStatusInformation,
DWORD dwStatusInformationLength)
{
REQUEST_CONTEXT* cpContext;
INTERNET_ASYNC_RESULT* res;
cpContext = (REQUEST_CONTEXT*)dwContext;
switch (dwInternetStatus)
{
case INTERNET_STATUS_HANDLE_CREATED:
res = (INTERNET_ASYNC_RESULT*)lpvStatusInformation;
hURL = (HINTERNET)(res->dwResult);
break;
case INTERNET_STATUS_REQUEST_COMPLETE:
InternetCloseHandle(hURL);
InternetSetStatusCallback(hInternetSession, NULL);
InternetCloseHandle(hInternetSession);
hURL = NULL;
hInternetSession = NULL;
break;
}
}
void RunScript(char* szURL)
{
if (hInternetSession == NULL)
{
hInternetSession = InternetOpen("Microsoft Internet Explorer",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
INTERNET_FLAG_ASYNC);
if (hInternetSession != NULL)
{
InternetSetStatusCallback(hInternetSession,
(INTERNET_STATUS_CALLBACK)InternetCallbackFunction);
hURL = InternetOpenUrl(hInternetSession,
szURL,
NULL,
0,
INTERNET_FLAG_RELOAD |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_NO_CACHE_WRITE,
(unsigned long)(&request_context));
}
}
}
History
- 24th August, 2007: Initial post