Search code examples
c++windowsmfcscreenshot

SetWindowDisplayAffinity not works in MFC windows


I have 1 Picture Control and want to make it not screen record-able.
In .Net, I have been using SetWindowDisplayAffinity:

WDA_MONTOR = 1;
SetWindowDisplayAffinity(this.Handle, WDA_MONTOR); 

Now I have moved to MFC for native performance.
I am using this following code which don't prevent screenshots:

HWND Handle = this->GetDlgItem(IDC_SCREEN)->m_hWnd;
SetWindowDisplayAffinity(Handle, WDA_MONITOR);

Complete example:

if(SetWindowDisplayAffinity(hWnd, WDA_MONITOR)==false)
{
    wchar_t buf[256];
    FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        buf, (sizeof(buf) / sizeof(wchar_t)), NULL);
    AfxMessageBox(buf);
}

GetLastError says "parameter is incorrect".


Solution

  • According to Raymond chen:

    The .NET version was passing the form's window handle (a top-level window), but your MFC version is passing a control's window handle (a child window). Use the top-level window.

    That's mean I would have to use Form handle instead of PictureBox handle. So change

    HWND Handle = this->GetDlgItem(IDC_SCREEN)->m_hWnd; //PictureBox handle
    SetWindowDisplayAffinity(Handle, WDA_MONITOR);
    

    to

    HWND Handle = this->m_hWnd;      //form handle
    SetWindowDisplayAffinity(Handle, WDA_MONITOR);
    

    Reason: Form window is parent and top-level window.