I am working on a set of UI Elements currently and the ComboBox is giving me a hard time.
My goal is to paint a 1px border around the element which will change color when the mouse hovers over it.
I used the WndProc()
Method to react to the WM_PAINT
Message and draw the border:
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)WindowsMessages.Win32Messages.WM_PAINT)
{
base.WndProc(ref m);
if (hovered || Focused)
{
//Paint frame with hovered color when being hovered over
PaintHelper.PaintFrame(this, _frameColorHovered, _frameWidth);
}
else
{
//Paint frame with standart color
PaintHelper.PaintFrame(this, _frameColor, _frameWidth);
}
}
.
.
.
}
Paint helper method looks as follows:
public static void PaintFrame(Control target, Color color, int frameWidth)
{
IntPtr dc = GetWindowDC(target.Handle);
using (Graphics g = Graphics.FromHdc(dc))
{
using (Pen p = new Pen(color, frameWidth))
g.DrawRectangle(p, frameWidth / 2, frameWidth / 2, target.Width - frameWidth, target.Height - frameWidth);
}
}
So far so good but the border keeps flickering when the mouse moves out or inside of the the Elements bounds! I did some research but everyone uses the UserPaint
flag which is not an option for me.
So: Is there any way to remove the flickering without painting the whole control myself?