1

I want to draw an image on transparent WinForms form.

On the first painting everything looks correct but once I start moving the form the "old" background is still painted.

Background picture: https://i.stack.imgur.com/K5iH1.png

On first painting after starting the program it gets painted fine with transparency:

enter image description here

But after moving the form:

enter image description here

using System;
using System.Drawing;
using System.Windows.Forms;

namespace TransparentImage
{
    public class Form1 : Form
    {
        private Image _image;

        public Form1()
        {
            TopMost = true;            
            FormBorderStyle = FormBorderStyle.None;
            StartPosition = FormStartPosition.CenterScreen;
            _image = Image.FromFile(@"C:\temp\image.png");
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            //empty implementation
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            // base.OnPaint(e);

            var g = e.Graphics;
            g.DrawImage(_image, Point.Empty);
        }

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();


        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); // drag event in window caption simulieren
            }
        }
    }
}
Jenny
  • 572
  • 4
  • 16

0 Answers0