DEV Community

海前 王
海前 王

Posted on

thread_copy_win32

`#include <windows.h>
#include <iostream>

DWORD WINAPI YourThreadFunction(LPVOID lpParam)
{
    HANDLE hSource = ::GetStdHandle(STD_OUTPUT_HANDLE); // 示例:原始句柄为标准输出句柄
    HANDLE hTarget = NULL; // 用于存储复制后的句柄

    if (::DuplicateHandle(::GetCurrentProcess(), hSource, ::GetCurrentProcess(), &hTarget, 0, FALSE, DUPLICATE_SAME_ACCESS))
    {
        // 成功复制句柄,使用 hTarget 作为复制后的句柄
        // 可以使用 hTarget 句柄进行操作

        // 示例:使用复制的句柄进行输出
        ::SetStdHandle(STD_OUTPUT_HANDLE, hTarget);
        std::cout << "This is printed using the duplicated handle." << std::endl;

        // 关闭复制的句柄
        ::CloseHandle(hTarget);
    }
    else
    {
        // 复制句柄失败
        DWORD lastError = GetLastError();
        // 处理错误
    }

    return 0;
}

int main()
{
    // 创建线程
    HANDLE hThread = ::CreateThread(NULL, 0, YourThreadFunction, NULL, 0, NULL);
    if (hThread == NULL)
    {
        // 创建线程失败
        DWORD lastError = GetLastError();
        // 处理错误
        return 1;
    }

    // 等待线程结束
    ::WaitForSingleObject(hThread, INFINITE);

    // 关闭线程句柄
    ::CloseHandle(hThread);

    // 示例:使用主线程的句柄进行输出
    std::cout << "This is printed using the original handle." << std::endl;

    return 0;
}`
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay