此代码适用于我,适用于 Windows 7 和 Windows XP。
#include <Windows.h>
void showcd(wchar_t * caption)
{
wchar_t buffer[512];
if (GetCurrentDirectory(512, buffer) == 0)
{
DWORD err = GetLastError();
MessageBox(NULL, L"GetCurrentDirectory failed", caption, MB_OK);
ExitProcess(err);
}
buffer[511] = L'\0';
MessageBox(NULL, buffer, caption, MB_OK);
}
void parent(wchar_t * cd)
{
wchar_t cmd[512];
wchar_t buffer[512];
STARTUPINFO sinfo;
PROCESS_INFORMATION pinfo;
GetStartupInfo(&sinfo);
showcd(L"Parent Process");
if (GetCurrentDirectory(512, buffer) == 0)
{
DWORD err = GetLastError();
MessageBox(NULL, L"GetCurrentDirectory failed", L"Parent Process", MB_OK);
ExitProcess(err);
}
buffer[511] = L'\0';
wcscat_s(buffer, 512, L"\\");
wcscat_s(buffer, 512, cd);
if (GetModuleFileName(NULL, cmd, 512) == 0)
{
MessageBox(NULL, L"GetModuleFileName failed", L"Parent Process", MB_OK);
ExitProcess(GetLastError());
}
cmd[511] = L'\0';
if (!CreateProcess(
cmd, NULL, NULL, NULL, FALSE, 0, NULL, buffer, &sinfo, &pinfo
))
{
DWORD err = GetLastError();
MessageBox(NULL, L"CreateProcess failed", L"Oops", MB_OK);
ExitProcess(err);
}
}
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
)
{
wchar_t * cmdline;
for (cmdline = GetCommandLine(); *cmdline; cmdline++)
{
if (*cmdline == L'*')
{
parent(cmdline + 1);
return 0;
}
}
showcd(L"Child Process");
return 0;
}
你可以像这样测试它:
C:\Documents and Settings\Administrator>dir
Volume in drive C has no label.
Volume Serial Number is 6080-CDD5
Directory of C:\Documents and Settings\Administrator
13/12/2012 09:56 a.m. <DIR> .
13/12/2012 09:56 a.m. <DIR> ..
18/05/2012 03:10 p.m. <DIR> Desktop
20/06/2008 11:45 a.m. <DIR> Favorites
19/10/2010 02:54 p.m. <DIR> My Documents
20/06/2008 04:15 a.m. <DIR> Start Menu
1 File(s) 43 bytes
6 Dir(s) 29,912,666,112 bytes free
C:\Documents and Settings\Administrator>\appendtocurrentdirectory.exe *My Documents