实例句柄和窗口句柄_句柄无效怎么处理

(5) 2024-06-21 10:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
实例句柄和窗口句柄_句柄无效怎么处理,希望能够帮助你!!!。

如果把GetCurrentThread()返回值传递给一个HANDLE句柄,用它进行ResumeThread,结果肯定不是我们想要的。下面的例子详细描述了伪句柄的调用结果:

#include "stdafx.h" #include <stdio.h> #include <iostream> #include <windows.h> #include <process.h> using namespace std; #pragma warning(disable:4996) HANDLE hThread = NULL; unsigned int __stdcall ProcessInfo(void* lp) { string str = *(string*)lp; delete lp; hThread = GetCurrentThread(); while(true){ SuspendThread(GetCurrentThread()); cout<<str.c_str()<<endl; } _endthreadex(0); return 0; } int _tmain() { string *pStr = new string; *pStr = "老婆, I Love You"; unsigned int dwThreadID; SECURITY_ATTRIBUTES sa; sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = NULL; sa.nLength = sizeof(SECURITY_ATTRIBUTES); HANDLE hCom = (HANDLE)_beginthreadex(&sa, 0, ProcessInfo, (void*)pStr, 0, &dwThreadID); Sleep(1000);//线程肯定会先执行到SuspendThread,主线程一直在延时,并且全局hThread得到线程的伪句柄 ResumeThread(hThread); printf("hThread的句柄值是: %d\n", hThread); Sleep(INFINITE); CloseHandle(hCom); return 0; }

结果显示,hThread是-2,线程没有输出任何东西

实例句柄和窗口句柄_句柄无效怎么处理_https://bianchenghao6.com/blog__第1张

修改代码如下:

#include "stdafx.h" #include <stdio.h> #include <iostream> #include <windows.h> #include <process.h> using namespace std; #pragma warning(disable:4996) HANDLE hThread = NULL; unsigned int __stdcall ProcessInfo(void* lp) { string str = *(string*)lp; delete lp; DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hThread, 0, 0, DUPLICATE_SAME_ACCESS); while(true){ SuspendThread(GetCurrentThread()); cout<<str.c_str()<<endl; } _endthreadex(0); return 0; } int _tmain() { string *pStr = new string; *pStr = "老婆, I Love You"; unsigned int dwThreadID; SECURITY_ATTRIBUTES sa; sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = NULL; sa.nLength = sizeof(SECURITY_ATTRIBUTES); HANDLE hCom = (HANDLE)_beginthreadex(&sa, 0, ProcessInfo, (void*)pStr, 0, &dwThreadID); Sleep(1000);//线程肯定会先执行到SuspendThread,主线程一直在延时,并且全局hThread得到线程的伪句柄 ResumeThread(hThread); printf("hThread的句柄值是: %d\n", hThread); Sleep(INFINITE); CloseHandle(hCom); return 0; } 

运行正常

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复