CreateDCW is crashing for Printer on worker thread

Shyam Butani 115 Reputation points
2024-05-15T07:18:16.3466667+00:00

Hi,

I want to print something using printer. For that I need to get the HDC of the printer like below:

HDC hdc = CreateDCW (NULL, L"Printer Name", NULL, NULL);

This is crashing with below error:

Exception thrown at 0x00007FFAE3B85B0C (KernelBase.dll) in TWTallySCPNative.exe: WinRT originate error - 0x80040155 : 'Failed to find proxy registration for IID: {79EAC9E4-BAF9-11CE-8C82-00AA004BA90B}.'.

But If I do winrt::init_apartment (apartment_type::single_threaded) before this, It works fine.

Can you please explain the reason behind this.

Printer name is valid (verified). This code is being executing on worker thread, can that be a problem?

Thanks.

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,451 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Jeanine Zhang-MSFT 9,266 Reputation points Microsoft Vendor
    2024-05-15T09:16:19.13+00:00

    Hello,

    Welcome to Microsoft Q&A!

    According to the Doc: CreateDCW function

    Note that the handle to the DC can only be used by a single thread at any one time.

    Refer to the Doc: Get started with C++/WinRT

    The call to winrt::init_apartment initializes the thread in the Windows Runtime; by default, in a multithreaded apartment.

    As far as I'm concerned, you need to call winrt::init_apartment to initializes the thread to single-threaded apartments in the Windows Runtime.

    Thank you.

    Jeanine


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. RLWA32 41,206 Reputation points
    2024-05-17T07:34:51.66+00:00

    I'm not able to reproduce the issue in another project. I'm not sure if any project properties that we've set might causing the issue. If I do init_apartment before CreateDC, CreateDC works but then StartDoc crashes.

    Apparently, the problem is in that specific project, not in the Windows API.

    Perhaps the need to initialize COM is unrelated to the Windows API printing functions. Have you tried using CoInitialize(Ex) instead of winrt::init_apartment?

    0 comments No comments