1

I want to add an image to the window's title bar. I know that is not possible with native Winforms tools but it should be able with the WinApi calls.

    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr GetWindowDC(IntPtr hwnd);
    [DllImport("user32.dll", SetLastError = true)]
    private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);

    protected override void WndProc(ref Message m)
    {
        IntPtr result = IntPtr.Zero;
        bool callDWP = !Win32Interop.DwmDefWindowProc(m.HWnd, m.Msg, m.WParam, m.LParam, out result);
        switch (m.Msg)
        {
            case Win32Messages.WM_NCPAINT:
                IntPtr hdc = GetWindowDC(m.HWnd); 
                if ((int)hdc != 0) 
                { 
                    Graphics g = Graphics.FromHdc(hdc); 
                    g.DrawImage(Resources.Logo, new Point(0, 0));
                    ReleaseDC(m.HWnd, hdc); 
                } 
            break;
        }

        m.Result = result;
        if (callDWP)
        {
            base.WndProc(ref m);
        }
    }

The image is not rendered. What am I doing wrong?

DerApe
  • 3,097
  • 2
  • 35
  • 55
  • I'm not sure if it will work, but You can try to Invaliadate() form – Kuba Do Feb 11 '20 at 10:40
  • Perhaps you need to call [`Graphics.Flush()`](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.flush?view=netframework-4.8)? That's what I find in other answers like [here](https://social.msdn.microsoft.com/Forums/en-US/950f3293-b329-492a-a1b8-d11b12f96c18/cant-change-mdi-child-title-bar-color-in-windows-10) or [here](https://stackoverflow.com/questions/11862315/changing-the-color-of-the-title-bar-in-winform) – orhtej2 Feb 11 '20 at 11:20
  • Unfortunately, that does not help :( – DerApe Feb 11 '20 at 12:08
  • Also, as stated in some of the answers comments it is no working in Windows 10 – DerApe Feb 11 '20 at 12:14
  • I figured the problem is caused by calling `base.WndProc()` after handling `WM_NCPAINT`. However, not calling it will leave drawing frame and menu up to you, and I assume you want to modify the default look? Calling it prior to custom logic makes window not update as it's already marked validated after call to base implementation so I'm not sure how to proceed here. Perhaps invalidate once more? – orhtej2 Feb 11 '20 at 19:14
  • @orhtej2 yea I figured that out too, but I was not able to solve my problem using this approach – DerApe Feb 12 '20 at 05:52
  • There are ways of drawing custom frame - see https://learn.microsoft.com/en-us/windows/win32/dwm/customframe for details, it's just a lot of P/Invokes and I'm not sure if there's no easier way. While there are NuGets that expose some of WDM functionality to .NET apps I was not able to find one making use of `DwmExtendFrameIntoClientArea` – orhtej2 Feb 12 '20 at 08:47

0 Answers0