前不久大家都在討論怎樣通過一個程序來生成另一個程序,我提出了將另一個程序當資源文件包含在程序中一起編譯,然後在程序運行時根據需要再重新生成出來,下面是我的一個例子, 在這裡,我將自帶的寫字板(writer.exe)當資源.
下面是源代碼
//資源文件writer.exe長度為204800,在資源文件中定義為"CUSTOM"資源,編號為1111
HRSRC hMyRes; //resource handle
HGLOBAL hgpt; //resource pointer
LPVOID lpBuff; //resource buffer pointer
DWORD rcSize=204800; //resource size
HANDLE hFile;//file to write
LPDWORD dwByte;//byte size had been write
dwByte=&rcSize; //locate the resource and load the resource to memory and lock it
hMyRes=FindResource((HMODULE)GetWindowLong(Handle,GWL_HINSTANCE),MAKEINTRE SOURCE(1111),"CUSTOM");
if(hMyRes==NULL)
ShowMessage(SysErrorMessage(GetLastError()));
hgpt=LoadResource(NULL,hMyRes);
if(hgpt==NULL)
ShowMessage(SysErrorMessage(GetLastError()));
lpBuff=LockResource(hgpt);
//now i will read the resource and write it to an file
try
{
hFile=CreateFile("e:\\mywriter.exe",GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
WriteFile(hFile,lpBuff,rcSize,dwByte,NULL);
if(*dwByte!=204800)
ShowMessage("Failed to write to file");
}
__finally
{
CloseHandle(hFile);
}
在資源的添加與生成時,我用Borland ResourceWorkShop4.5沒辦法做,最後是用vb6帶的資源編輯器生成的res文件.