I need to run for example:
ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE);
as new thread, but I don't know how. I tried this:
HANDLE hThread = (HANDLE) _beginthread(ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE), 0, NULL);
WaitForSingleObject( hThread, INFINITE );
but obviously it's wrong and can't be compiled. How should I do this?
What you tried is indeed obviously wrong, but the question is whether you understand what's wrong with it.
_beginthreadtakes a pointer to function (with a specific prototype and calling convention) as its first parameter.When you write
you're trying to pass
_beginthreadthe result of callingShellExecute(in the current thread) which is anHINSTANCE, while_beginthreadexpects avoid( __cdecl *)( void * )(pointer to a__cdeclfunction taking onevoid*parameter and returningvoid).Not only your code doesn't work because you're trying to pass an
HINSTANCEwhere a function to pointer is expected, it doesn't make any sense. Have you read the_beginthreaddocumentation? There are examples there. Plural.What you meant to write is:
given:
Or, in a more compact and easy to read form:
Unless you're doing something beyong what we're seeing here, David'scomment is probably right and you should be using
std::threadorstd::async.Also note that taking the result of
_beginthread(int contrast to the result of_beginthreadexorCreateThread) in unsafe because it may not be valid, as noted in the documentation. Not only that, but_beginthread's return value isn't really aHANDLE(it is some sore of a handle, but not aHANDLE!), so you can'tWaitForSingleObjecton it:Since this thread only calls one function and exits, it almost maximizes the chance of this handle not being valid. And even if it were, you still couldn't use it to
WaitForSingleObject.