不要在DllMain创建线程,因为在DllMain里的代码会被反复执行。可以单独使用个函数来启动线程,下面是我写的一个让PC喇叭每隔1秒响一次的DLL代码,你可以参考
#include "stdafx.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//全局变量
BOOL api_nThreadFlag = TRUE;//线程运行标志
DWORD __stdcall Thread(LPVOID wParam);
__declspec(dllexport) void WINAPI StartThread()
{
//启动线程
DWORD dwThreadId;
api_nThreadFlag = TRUE;
HANDLE hThread;
hThread = CreateThread(NULL, 0, Thread, NULL, 0, &dwThreadId);
CloseHandle(hThread);
}
__declspec(dllexport) void WINAPI EndThread()
{
api_nThreadFlag = FALSE;
}
DWORD __stdcall Thread(LPVOID wParam)
{
while(api_nThreadFlag)
{
Beep(1000,1000);
Sleep(1000);
}
return 0;
}