views:

1243

answers:

6

I am creating a Windows Forms control derived from UserControl to be embedded in a WPF app. I have generally followed the procedures given in this link.

public ref class CTiledImgViewControl : public UserControl
{
...

virtual void OnPaint( PaintEventArgs^ e ) override;

...
};

And in my CPP file:

void CTiledImgViewControl::OnPaint( PaintEventArgs^ e )
{
    UserControl::OnPaint(e);
    // do something interesting...
}

Everything compiles and runs, however the OnPaint method is never getting called.

Any ideas of things to look for? I've done a lot with C++, but am pretty new to WinForms and WPF, so it could well be something obvious...

A: 

Are you missing the override keyword at the end of your method

void CTiledImgViewControl::OnPaint( PaintEventArgs^ e ) override
benPearce
I took this code from the page referenced in the link in the question. Can't understand why everyone voted it down so rapidly.
benPearce
I think it was voted down as it didn't solve the question.
Jeff Yates
A: 

@benPearce: This is C++/CLI, and the override keyword, like the virtual keyword, evidently can only be specified in the header file, not in the implementation (CPP) file.

Brian Stewart
+1  A: 

The OnPaint won't normally get called in a UserControl unless you set the appropriate style when it is constructed using the SetStyle method. You need to set the UserPaint style to true for the OnPaint to get called.

SetStyle(ControlStyles::UserPaint, true);


Update

I recently encountered this issue myself and went digging for an answer. I wanted to perform some calculations during a paint (to leverage the unique handling of paint messages) but I wasn't always getting a call to OnPaint.

After digging around with Reflector, I discovered that OnPaint is only called if the clipping rectangle of the corresponding WM_PAINT message is not empty. My UserControl instance had a child control that filled its entire client region and therefore, clipped it all. This meant that the clipping rectangle was empty and so no OnPaint call.

I worked around this by overriding WndProc and adding a handler for WM_PAINT directly as I couldn't find another way to achieve what I wanted.

Jeff Yates
A: 

@ffpf: OK - I set the style first thing in the constructor, but the OnPaint method is still not getting called.

It seems eminently possible that I missing some other style or other initialization step. Any other ideas?

Brian Stewart
+1  A: 

I solved the issue, in case anyone is interested. It was because my WinForms control was embedded in a ViewBox. I changed it to a grid and immediately started getting paint events. I guess when asking questions about WPF, you should always include the XAML in the question!

Brian Stewart
A: 

I am having this problem but I am using .Net Compact Framework.

There's no SetStyle method. Any other solution ?

Niko Gunadi