2013年3月3日星期日

x64_Redirector.cpp


#include <Windows.h>

typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);

LPFN_ISWOW64PROCESS fnIsWow64Process;

BOOL IsWow64()
{
    BOOL bIsWow64 = FALSE;

    //IsWow64Process is not available on all supported versions of Windows.
    //Use GetModuleHandle to get a handle to the DLL that contains the function
    //and GetProcAddress to get a pointer to the function if available.

    fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")),"IsWow64Process");
    if(NULL != fnIsWow64Process)
    {
        if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
        {
            //handle error
        }
    }
    return bIsWow64;
}

int _tmain(int argc, _TCHAR* argv[])
{
    HKEY var;
    wchar_t dir[] = L"testtest";

    REGSAM  rs;

    if (IsWow64())
    {
        rs = KEY_ALL_ACCESS | KEY_WOW64_64KEY;
    }
    else
    {
        rs = KEY_ALL_ACCESS;
    }

    if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows\\CurrentVersion\\Run",0,0,REG_OPTION_NON_VOLATILE,rs,0,& var,0) != ERROR_SUCCESS)
    {
        MessageBox(0,L"RegCreateKeyEx 失败",0,0);
    }

    RegDisableReflectionKey(var);//这个函数也会返回失败。

    if (RegSetValueEx(var,L"dp-ips",0,REG_SZ,(const BYTE *)dir,lstrlen(dir) * sizeof (wchar_t)) != ERROR_SUCCESS)
    {
        MessageBox(0,L"RegSetValueEx 失败",0,0);
    }

    RegEnableReflectionKey(var);//这个函数也会返回失败。

    if (RegCloseKey(var) != ERROR_SUCCESS)
    {
        MessageBox(0,L"RegCloseKey 失败",0,0);
    }

 return 0;
}

/*
更通用的是如下代码:
__inline bool Is32BitProcessRunningOnWow64()
{
#ifdef _WIN64
    // 64-bit code, obviously not running in a 32-bit process
    return false;   
#else
    BOOL fWow64Process;
    return IsWow64Process(GetCurrentProcess(), &fWow64Process) &&        IfWow64Process;
#endif
}

扩展资料:

Registry Redirector:
http://msdn.microsoft.com/en-us/library/aa384232(v=vs.85).aspx

Example of Registry Redirection on WOW64 (Windows)
http://msdn.microsoft.com/en-us/library/windows/desktop/aa384182(v=vs.85).aspx

Registry Redirector 的函数:
RegEnableReflectionKey
RegDisableReflectionKey


File System Redirector (Windows) http://msdn.microsoft.com/en-us/library/windows/desktop/aa384187(v=vs.85).aspx
Wow64DisableWow64FsRedirection   http://msdn.microsoft.com/en-us/library/aa365743(VS.85).aspx
Wow64EnableWow64FsRedirection
Wow64RevertWow64FsRedirection

估计这是32位的程序运行在64为系统下出现的问题,64位的程序运行在64位的系统应该不会出现这问题。
2013.03.03
*/