KeithS
KeithS

Reputation: 71573

Stop .NET painting on a Panel to let unmanaged code paint

I have an SDK in unmanaged code that I'm using in a .NET Winforms GUI program. The SDK paints images on Panels that I pass in by handle to the SDK. However, it's still a .NET control, contained within wholly managed GUI elements.

The problem I'm having is that when the main window gets redrawn, my program (and the .NET runtime) repaints these Panels, which happens after the unmanaged code redraws the image on the panel. That overwrites the image I expect with the "background" set up in the Designer.

After giving the panel to my SDK, I want to stop .NET repainting them. But, I need to keep the resizing behavior.

I tried the simple approach, which was to derive "MyPanel" from the Panel, adding custom code that controls the OnPaint() method:

public class MyPanel : Panel
{
    [Category("Behavior"), DefaultValue(true)]
    public bool LetNetPaint { get; set; }

    protected override void OnPaint(PaintEventArgs e)
    {
        if(LetNetPaint)
            base.OnPaint(e);
    }
}

This does not work, however.

I also tried intercepting the WM_PAINT and WM_ERASEBKGND messages in WndProc(), and that's... better, but not great.

I'm at a loss; this simply must work or a lot of hard work goes down the drain and a lot of harder work begins to implement a different solution from scratch.

Upvotes: 1

Views: 231

Answers (1)

KeithS
KeithS

Reputation: 71573

As the answer to my own question, here's the code that ended up working, based on Hans Passant's SetStyle suggestion:

public class NativeDrawingPanel : Panel
{
    private bool letNetPaint;

    [Category("Behavior"), DefaultValue(true)]
    public bool LetNetPaint
    {
        get { return letNetPaint; }
        set 
        { 
            letNetPaint = value;
            SetStyle(ControlStyles.UserPaint, value);
            if(value) Refresh();
        }
    }

    public NativeDrawingPanel()
    {
        letNetPaint = true;
        SetStyle(ControlStyles.UserPaint, true);
    }
}

Upvotes: 1

Related Questions