我们的软件在使用的时候有一个功能就是向某一个可执行文件的一个资源里面写入一个
字符串,这个字符串其实就是我们的软件的服务器的地址,这样那个可执行文件也就是我们
的客户端就不用手动的输入服务器ip就可以根据那个写入的字符串进行和服务器的连接。
在网上找了很多的例子也不行,后来找到了这个函数,只需向里面传入参数就可以实现,但
是这个字符串的ID是固定的,就是1,也就是说这个固定的ID是不能改变的
BOOL SetScreenSaverName(LPCTSTR szSSPath, LPCTSTR szSSName)
{
//szSSPath是可执行文件的完整路径
//szSSName是要写入的字符串
HANDLE h = ::BeginUpdateResource(szSSPath,FALSE);
if(!h)
{
// BeginUpdateResource failed
return FALSE;
}
CString sNewString = szSSName;
int iCharCount = sNewString.GetLength() + 1;
LPWSTR pUnicodeString = new WCHAR[iCharCount];
if(!pUnicodeString)
{
// new failed
return FALSE;
}
DWORD dwUnicodeCharCount =
MultiByteToWideChar(CP_ACP, NULL, sNewString.GetBuffer(0),
-1, pUnicodeString, iCharCount);
HGLOBAL hGlob =
GlobalAlloc(GHND, (dwUnicodeCharCount + 4) * sizeof(WCHAR) );
if(!hGlob)
{
// GlobalAlloc failed
delete pUnicodeString;
return FALSE;
}
LPWSTR pBufStart = (LPWSTR)GlobalLock(hGlob);
if(!pBufStart)
{
// GlobalLock failed
GlobalFree(hGlob);
delete pUnicodeString;
return FALSE;
}
LPWSTR pBuf = pBufStart;
pBuf++;
// offset to make it string ID=1. Increment by more
// to change to a different string ID
// next 2 bytes is string length
*(pBuf++) = (WCHAR)dwUnicodeCharCount-1;
for(int i=0; i<(int)dwUnicodeCharCount-1; i++)
// remaining bytes are string in wide chars (2 bytes each)
*(pBuf++) = pUnicodeString[i];
delete pUnicodeString;
if(++dwUnicodeCharCount % 1)
// make sure we write an even number
dwUnicodeCharCount++;
BOOL bSuccess = TRUE;
if(!::UpdateResource(h, RT_STRING, MAKEINTRESOURCE(1),
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
pBufStart, dwUnicodeCharCount * sizeof(WCHAR) ) )
{
// UpdateResource failed
bSuccess = FALSE;
}
GlobalUnlock(hGlob);
GlobalFree(hGlob);
::EndUpdateResource(h, FALSE); // write changes
return bSuccess;
}
然后在程序里面可以这样调用
SetScreenSaverName("c://a.exe","这是一个测试的字符串");
然后在a.exe里面这样测试
CString str;
str.LoadString(1);
AfxMessageBox(str);
这样就可以看到效果了
2007-11-24 13:23:42