设置剪贴板数据导致程序C win32崩溃



我试着用一个字符串来垃圾邮件我的客户电脑的剪贴板。当我的服务器/客户端在同一台机器上运行时,它可以工作。但是当我把客户端程序移到另一台机器上时,它就崩溃了,没有任何错误代码。我怎样才能垃圾邮件的剪贴板的客户端没有我的客户端程序崩溃每次?

服务器:

while (1)
{
HANDLE buf = malloc(1048);
r = recv(s, (char*)buf, 1048, 0);
if (r == SOCKET_ERROR)
{
printf("error receiving clipboard datan");
goto jumpThree;
}
printf("%sn", (char*)buf);
if (strncmp((char*)buf, "test", 4) == 0)// if we got the respond we expected
{
break;
}
free(buf);
Sleep(1000);
}

客户:

while (1)
{
const wchar_t* strData = L"I am spamming you";
if (OpenClipboard(0)) {

HANDLE h = GetClipboardData(CF_TEXT);

if (strncmp((char*)h, "test", 4) == 0)
{
printf("TEST: %sn", (char*)h);
int r = send(ClientSocket, (char*)h, 75, 0);
if (r == SOCKET_ERROR)
{
printf("error sending clipboard datan");
goto jumpThree;
}
CloseClipboard();
}

HGLOBAL hClipboardData;
hClipboardData = GlobalAlloc(GMEM_DDESHARE, sizeof(WCHAR) * (wcslen(strData) + 1));
WCHAR* pchData;
pchData = (WCHAR*)GlobalLock(hClipboardData);
wcscpy(pchData, strData);
GlobalUnlock(hClipboardData);
SetClipboardData(CF_UNICODETEXT, hClipboardData);
CloseClipboard();
}
Sleep(1000);
}

在文档中,它说当你用OpenClipboard()NULL参数调用EmptyClipboard()时,SetClipboardData()崩溃。但是我没有调用EmptyClipboard(),所以我认为这不是问题。

编辑:我发现这是因为if else语句。我现在正在寻找一个修复。

我不知道我必须检查GetClipboardData()是否返回NULL。因为如果它返回NULL,程序在尝试对字符串执行操作时崩溃,就像下面这行:if (strncmp((char*)h, "test", 4) == 0)。因此,我将这段代码添加到我的客户机程序中:

HANDLE h = GetClipboardData(CF_TEXT);
if (h == NULL)
{
printf("h is nulln");
Sleep(1000);
/* Do something here. Like go try GetClipboardData() again */
}

谢谢大家的帮助!

最新更新