windows下c++多线程的实现
发布网友
发布时间:2022-04-25 16:04
我来回答
共2个回答
热心网友
时间:2023-10-15 19:30
我最近写的,别看regist()函数就满足你的要求:
//
//Created by ABacker on 5/31/2016 --VS2013
//
//打开此程序,3秒后关闭显示器并退出程序
//此程序会在桌面"我的电脑"右键中添加"关闭显示器"选项
//
#include<thread>
#include<vector>
#include<conio.h>
#include<tchar.h>
#include<stdio.h>
#include<windows.h>
#include<iostream>
using namespace std;
#define HIDE 1// 0 ---- 非隐藏运行,输出到标准设备
// 1 ---- 隐藏运行,输出到Log.txt
#if(HIDE)
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")//隐藏运行
#endif
//修改注册表,在桌面"我的电脑"右键中添加"关闭显示器"选项
bool regist() {
HKEY hkey, closekey, cmdkey;
LPTSTR path = TEXT("CLSID\\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\shell");
//获取此程序全路径
char exePath[MAX_PATH];
GetMoleFileNameA(NULL, (LPSTR)exePath, sizeof(char)*MAX_PATH);
//char * to wchar_t *
int num = MultiByteToWideChar(0, 0, exePath, -1, NULL, 0);
wchar_t *_exePath = new wchar_t[num];
MultiByteToWideChar(0, 0, exePath, -1, _exePath, num);
//在注册表path下创建 Key:"关闭显示器",在"关闭显示器"下创建Key:"command",设置"command"下的默认值为REG_EXPAND_SZ:_exePath
if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CLASSES_ROOT, path, 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, &hkey)) {
if (ERROR_SUCCESS == ::RegCreateKeyEx(hkey, TEXT("关闭显示器"), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS | KEY_WOW64_64KEY, NULL, &closekey, NULL)) {
if (ERROR_SUCCESS == ::RegCreateKeyEx(closekey, TEXT("command"), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS | KEY_WOW64_64KEY, NULL, &cmdkey, NULL)) {
if (ERROR_SUCCESS == ::RegSetValueEx(cmdkey, TEXT(""), 0, REG_EXPAND_SZ, (CONST BYTE *)_exePath, sizeof(wchar_t)*num)) {
return true;
}
else printf("error:regist setvalue!\n");
::RegCloseKey(cmdkey);
}
else printf("error:regist create key command!\n");
::RegCloseKey(closekey);
}
else printf("error:regist create key 关闭屏幕!\n");
::RegCloseKey(hkey);
}
else printf("error:regist open key!\n");
delete[] _exePath;
return false;
}
//新线程入口
DWORD WINAPI ThreadEntrance(LPVOID p) {
if (!regist())printf("regist false!\n");
printf("The screen will be off in 3s...\n");
Sleep(3000);
SendMessage(FindWindow(0, 0), WM_SYSCOMMAND, SC_MONITORPOWER, 2);//关闭显示器
#if!(HIDE)
printf("It will be closed in 10s...\n");
Sleep(10000);
#endif
ExitThread(0);
return 0;
}
int main() {
#if(HIDE)
freopen("Log.txt", "w", stdout);
#endif
//在新线程中运行是为了防止程序打开时处于无响应Sleep状态使鼠标指针变为等待
DWORD ID;
HANDLE hand = CreateThread(0, 0, ThreadEntrance, NULL, 0, &ID);
WaitForSingleObject(hand, INFINITE);//等待线程退出
return 0;
}
热心网友
时间:2023-10-15 19:30
CreateThread( )