VCL custom TGraphicControl messes up only on a remote desktop - c++

In a C++ application (using C++Builder 10.3 and VCL), I use a custom class derived from TGraphicControl to draw a custom user interface and a small plot of changing data.
Everything works well in Windows 10 and Windows 7, but if I execute the application in a Remote Desktop session (via a native Windows service) with each redraw the graphics are messed up more.
The problem starts with disappearing elements and wrong LineTo endpoints, but sometimes the elements appear even in a different dialog instead.
Also, switching on a PC from direct to remote access causes dynamically inserted VCL TComboBox elements to get invalid parents and owners, followed by an error message that the TComboBox class is unknown.
I'm using ClientRect in my code. Is this perhaps the problem when working in remote sessions?
Code where I see the problem (it's a bit long and I have trouble making a minimal example without omitting possible causes of the problem)
cpp: https://pastebin.com/vpk3De7J (painter at line 228)
header: https://pastebin.com/3pLy4dEY
class CustomTrgDrawings : public TGraphicControl
{
private:
void __fastcall Paint(void);
public:
__fastcall CustomTrgDrawings(TComponent* Owner);
bool updating; //stops painting when true
};
__fastcall CustomTrgDrawings::CustomTrgDrawings(TComponent* Owner)
: TGraphicControl(Owner)
{
updating = true;
}
void __fastcall CustomTrgDrawings::Paint(void)
{
if (!updating)
return;
Canvas->Brush->Color = TColor(0x220022);
Canvas->Brush->Style = bsSolid;
Canvas->Pen->Color = TColor(0x222222);
Canvas->Pen->Style = psSolid;
Canvas->Pen->Width = 1;
Canvas->FillRect(ClientRect);
}
//---insertion in a vcl form
void __fastcall TMyForm::FormCreate(TObject *Sender)
{
//uses TLabel *myLabel as container
CustomTrgDrawings *drg = new CustomTrgDrawings(myLabel);
}

Related

OLE Automation - Ghost Excel Instance in Task Manager

I am using wxAutomationObject to export data to MS Excel. I have created a few helper classes ExcelApp, ExcelWorkbook etc... all of which inherits from wxAutomationObject.
Briefly, ExcelApp is as follows:
class ExcelApp :public wxAutomationObject
{
public:
ExcelApp(WXIDISPATCH* dispatchPtr = NULL);
~ExcelApp() = default;
void Quit();
std::unique_ptr<ExcelWorkbook> CreateWorkbook(bool Visible = true);
std::vector<std::unique_ptr<ExcelWorkbook>> GetOpenedWorkbooks();
long GetNumberofOpenedWorkbooks() const;
private:
wxAutomationObject m_App;
};
The constructor is implemented as follows:
ExcelApp::ExcelApp(WXIDISPATCH* dispatchPtr):wxAutomationObject(dispatchPtr)
{
if (!m_App.GetInstance("Excel.Application"))
throw std::exception("An instance of Excel object could not be created.");
}
And to create a workbook, I used to following code:
std::unique_ptr<ExcelWorkbook> ExcelApp::CreateWorkbook(bool Visible)
{
auto wb = std::make_unique<ExcelWorkbook>();
bool suc = m_App.GetObject(*wb, "Workbooks.Add");
if (!suc)
return nullptr;
if (Visible)
m_App.PutProperty("Visible", true);
return std::move(wb);
}
This whole OLE implementation is part of a dynamic menu. Part of the code for the event handler for menu is:
void MyFrame::OnExportToExcelButtonHandler(wxCommandEvent& event)
{
auto item = static_cast<wxMenu*>(event.GetEventObject());
std::unique_ptr<ExcelWorkbook> xlsWB ((ExcelWorkbook*)event.GetEventUserData());
bool CreateNewWB = false;
try
{
//Export either the entire workbook or the active worksheet to a new Workbook
if (xlsWB == nullptr)
{
auto xlsApp = ExcelApp();
xlsWB = std::move(xlsApp.CreateWorkbook());
CreateNewWB = true;
}
In terms of exporting data and formatting, everything works fine. However, after closing the created Workbooks Excel.exe still remains in the taskbar list. I wonder what I could be missing?
By the way, I tried the very basic sample shipped with wxWidgets and there seems to remain no ghost instances of Excel after quitting. I
I am using wxWidgets 3.1.4 on Windows 10 using VS 2019.
EDIT 1:
The ribbon button that generates the dynamic menu:
void MyFrame::OnExportToExcelButtonClicked(wxRibbonButtonBarEvent& event)
{
auto excel = sys::win32::ole::ExcelApp();
auto PrepareMenu = [&](wxMenu* Menu)
{
try
{
wxMenuItem* item1 = Menu->Append(wxID_ANY, "New Excel Workbook");
item1->SetBitmap(wxArtProvider::GetBitmap(wxART_NEW));
Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExportToExcelButtonHandler, this, item1->GetId());
auto wbs = excel.GetOpenedWorkbooks();
if (wbs.size() > 0)
{
for (int i = 0; i < wbs.size(); ++i)
{
auto ExcelWB = std::move(wbs[i]);
wxMenuItem* item1 = Menu->Append(wxID_ANY, ExcelWB->GetFullName());
Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExportToExcelButtonHandler, this, item1->GetId(), wxID_ANY, ExcelWB.release());
}
}
}
}
The problem seems to originate from the following line:
Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExportToExcelButtonHandler, this, item1->GetId(), wxID_ANY, ExcelWB.release());
The ExcelWB pointer is now owned by the wxWidgets system and therefore a reference remains and thus the ghost Excel.exe remains.
To solve it, in the following procedure I added:
void MyFrame::OnExportToExcelButtonHandler(wxCommandEvent& event)
{
Unbind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExportToExcelButtonHandler, this, event.GetId(), wxID_ANY, xlsWB.get());
But the problem still remains. I am not sure how to properly get rid of the pointer that is now owned by the menu. I redesigned some parts with shared_ptr and it did not help.
You already may be doing that but just to be sure.
When debugging such things, make sure the application instance is always visible so you can see when it for example gets stuck waiting on a user input, e.g., asking to save a modified workbook, preventing it from quitting.
I have written wxWidgets-based MS Excel automation wrapper wxAutoExcel (it uses a shared instead of unique pointer for Excel objects) and I have never encountered application ghosts, except when I terminated my application when debugging, without disposing Excel objects.
BTW, I do not get why your ExcelApp both derives from wxAutomationObject and has wxAutomationObject as a member variable (m_App). What is the IDispatch used in the ExcelApp ctor for?
Finally, it seems like I solved the issue, using the following steps:
Instead of a menu, now a dialog is used; therefore, the menu does not own the pointer anymore.
All wxAutomationObject inheriting objects are passed around via std::unique_ptr.

QML OpenGL plugin not redrawing at 60Hz

The Situation
My company has a QML-based application which displays some content using a custom OpenGL-based render plugin (MyGame). This plugin has a few critical needs:
To be able to effect changes in the renderer in response to QML-based signals.
(e.g. change the position of an object rendered by the game)
To only process these changes at a specific spot in MyGame's redraw loop.
(This is very important; MyGame is very sensitive about when changes are allowed.)
To have the plugin redraw at 60Hz (at least).
The Problem
The code we have right now honors (1) and (2), but fails (3); the plugin does not get visually updated consistently. (The updates are erratic, at an estimated 5-10Hz.) I believe that the plugin we have created—based on QQuickFramebufferObject—is not taking proper advantage of how Qt/QML intended the scene graph to be updated.
How can I re-structure my plugin so that I get all three of the above?
The Code
Overview:
The plugin creates a QQuickFramebufferObject (MyPlugin) and a QQuickFramebufferObject::Renderer (MyRenderer).
When MyRenderer::render() is called it calls MyGame::Redraw() itself, and then calls update().
MyGame::Redraw() does what it needs to, and at the right spot where changes can be accepted, emits a timeToMakeChanges QML signal on MyPlugin.
QML listens for the onTimeToMakeChanges signal and invokes methods on the plugin that affect MyGame.
To workaround the problem of low-frequency visual updates, I've found that if I overlay a QML Canvas over my plugin and redraw the canvas frequently using a Timer, my plugin starts to get visually updated at what appears to be around 60Hz. Clearly this is a gross hack.
Following is a summary of the code setup. Please forgive missing/incorrect code; I'm trying to distill thousands of lines of glue code down to the essentials for this question.
MyPlugin.h
#include <QOpenGLFramebufferObject>
#include <QQuickFramebufferObject>
class MyPlugin : public QQuickFramebufferObject {
Q_OBJECT
public:
MyPlugin();
virtual ~MyPlugin();
virtual QQuickFramebufferObject::Renderer* createRenderer() const;
signals:
void timeToMakeChanges();
public slots:
void makeChanges(QVariant inValue);
void HandleWindowChanged(QQuickWindow *inWindow);
private:
MyGame* GetGame() { ... }
};
MyPlugin.cpp
#include "MyPlugin.h"
#include <MyGame.h>
// ******************************************************************
class MyRenderer:
public QObject,
public QQuickFramebufferObject::Renderer,
protected QOpenGLFunctions
{
Q_OBJECT
public:
virtual void render();
private:
static void RequestGameChanges();
};
void MyRenderer::render() {
if ( !m_Initialized ) {
QOpenGLFramebufferObject *theFbo = this->framebufferObject();
InitializeGl( theFbo ); // Not shown
m_MyGame = &MyGame::Create();
m_MyGame->RegisterCallback(
reinterpret_cast<qml_Function>(MyRenderer::RequestGameChanges)
);
m_Initialized = true;
}
m_MyGame->RestoreState();
m_MyGame->Redraw();
m_MyGame->SaveState();
m_PluginItem->window()->resetOpenGLState();
// Tell QML that we want to render again as soon as possible
update();
}
// This gets invoked in the middle of m_MyGame->Redraw()
void MyRenderer::RequestGameChanges() {
emit m_PluginItem->timeToMakeChanges();
}
// ******************************************************************
MyPlugin::MyPlugin() {
setMirrorVertically(true);
connect(
this, SIGNAL(windowChanged(QQuickWindow*)),
this, SLOT(HandleWindowChanged(QQuickWindow*))
);
}
void MyPlugin::HandleWindowChanged(QQuickWindow *inWindow) {
inWindow->setClearBeforeRendering(false);
}
void MyPlugin::makeChanges(QVariant inValue) {
MyGame *theGame = GetGame();
// Send the requested changes to theGame
}
QQuickFramebufferObject::Renderer* MyPlugin::createRenderer() const {
m_Renderer = new MyRenderer( *this );
}
MyApp.qml
import MyPlugin 1.0
Window {
MyPlugin {
property var queuedUpChanges: ([])
onSomeOtherSignal: queueUpChangesToMake();
onTimeToMakeChanges: makeChanges( queuedUpChanges );
}
Canvas { id:hack }
Timer {
interval:10; running:true; repeat:true
onTriggered: hack.changeWhatYouShow();
}
}
Bonus Points
The main question is "How do I modify my code so that I get 60Hz updates?" However, as seen in the QML, the setup above requires me to queue up all changes in QML so that they are able to be applied during the right spot in the MyGame::Render().
Ideally, I'd prefer to write QML without timeToMakeChanges, like:
MyPlugin {
onSomeOtherSignal: makeChanges( ... );
}
If there's a way to accomplish this (other than queuing up the changes in C++ instead)—perhaps something related to synchronize() I'd love to know about it.
I'd make a timer in QML that calls the makeChanges regularly. But store all the state in MyPlugin. Then, in Renderer::synchronize(), copy from MyPlugin to MyRenderer, so it can be used by the MyGame.
(although, I wouldn't do any gamelogic-related calculations in QML ever in the first place)

ActiveX and COM for interprocess communication

I have a closed source program that generates ActiveX events, and I need to modify mine so that these events can be received. So we have two separate executables, and no GUI stuff is used. So far I got to this point, which only works if the event is generated and received by the same process:
[event_source(native)]
class CSource {
public:
__event void MyEvent(int nValue);
};
[event_receiver(native)]
class CReceiver {
public:
void MyHandler(int nValue) { ... }
void hookEvent(CSource* pSource) {
__hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler);
}
void unhookEvent(CSource* pSource) {
__unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler);
}
};
int main() {
CSource source;
CReceiver receiver;
receiver.hookEvent(&source);
__raise source.MyEvent(123);
receiver.unhookEvent(&source);
}
Now, the event_source is in the application I need to interface with. How can I connect the receiver and the source when they are in two separate processes?
Either an explanation or some references will be useful.
You don't want attributed C++ since even though it is still supported, reality is that it has been deprecated since at the very least VS 2008
You need event_receiver(com, not native type since ActiveX events are in question
The items above suggest that you don't use attributes and instead use IDispEventImpl or IDispEventSimpleImpl class to implement receiver of ActiveX control events (the article gives code snippet and references sample project).

WPF World Editor for my DirectX game engine

I am working on a small game and game engine in C++ using DirectX. The purpose is educational & recreational.
My next goal is to build a simple world editor that uses the game engine. For this I will need to move the engine into a dll so it can be consumed by the game and/or by the editor. The world editor will be a stand-alone tool and not part of the game. The main purpose of the world editor will be to read in and display my (custom) scene file, and allow me to annotate/modify properties on world objects (meshes), clone objects, pick up and move objects about and drop them, scale objects, etc., and then save out the modified scene so it can later be read by the game.
It has been recommended that I use wxWidgets for the editor. A bit of research makes me feel that wxWidgets is a bit old and clunky, though I am sure very fine GUIs can be written using it. It's just a steep learning curve that I don't look forward to. I have gotten the samples to build and run, but it was a headache.
A little more research and I find that I can integrate DirectX into a WPF app using a D3DImage. I have done a little with WPF and do not find it too intimidating and there are plenty of good books available (there is only one old one for wxWidgets), as well as scads of information on the web. I have gotten the rotating triangle example working and it seemed pretty straightforward.
So my question is:
Will WPF allow me to build a decent little world editor app that re-uses my game engine?
My game engine currently uses RawInput for mouse and keyboard; how will this work with WPF?
How does WPF affect my message pump?
It looks like I will have to write a lot of functions (facade pattern?) to allow WPF to interact with my game engine. Is there an easy way to factor this out so it doesn't get compiled into the game?
Any other tips or ideas on how to proceed would be greatly appreciated!
Thank you.
You need to create a wrapper class that exposes certain functionality of your game.
For example. This function is in my c++ game engine editor wrapper.
extern "C" _declspec(dllexport) void SetPlayerPos(int id, const float x, const float y, const float z);
Then in your c# wpf application you can create a static class allowing you to use those functions
[DllImport(editorDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void SetPlayerPos(int id, float x, float y, float z);
You will have to have functions for your basic functionality of the game engine through the dll.
things like
EditorMain
RenderFrame / Update
DXShutdown
So then you can call editormain in your wpf app constructor
System.IntPtr hInstance = System.Runtime.InteropServices.Marshal.GetHINSTANCE(this.GetType().Module);
IntPtr hwnd = this.DisplayPanel.Handle;
NativeMethods.EditorMain(hInstance, IntPtr.Zero, hwnd, 1, this.DisplayPanel.Width, this.DisplayPanel.Height);
You will need to create a message filter class and initialize it in the constructor as well
m_messageFilter = new MessageHandler(this.Handle, this.DisplayPanel.Handle, this);
here's how your message filter class could look
public class MessageHandler : IMessageFilter
{
const int WM_LBUTTONDOWN = 0x0201;
const int WM_LBUTTONUP = 0x0202;
IntPtr m_formHandle;
IntPtr m_displayPanelHandle;
EngineDisplayForm m_parent;
public MessageHandler( IntPtr formHandle, IntPtr displayPanelHandle, EngineDisplayForm parent )
{
m_formHandle = formHandle;
m_displayPanelHandle = displayPanelHandle;
m_parent = parent;
}
public bool PreFilterMessage(ref Message m)
{
if (m.HWnd == m_displayPanelHandle || m.HWnd == m_formHandle)
{
switch (m.Msg)
{
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
{
NativeMethods.WndProc(m_displayPanelHandle, m.Msg, m.WParam.ToInt32(), m.LParam.ToInt32());
if (m.Msg == WM_LBUTTONUP)
{
m_parent.SelectActor();
}
return true;
}
}
}
return false;
}
public void Application_Idle(object sender, EventArgs e)
{
try
{
// Render the scene
NativeMethods.RenderFrame();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
for doing win forms and wpf interop look here
http://msdn.microsoft.com/en-us/library/ms742474.aspx

Transparent background for MFC-hosted Windows Forms UserControl

I am using CWinFormsControl to host a Windows Forms UserControl in an MFC dialog. I have set the property DoubleBufferd to true. According to the docs this results in AllPaintingInWmPaint and UserPaint to be set to true too (not sure if this matters). How can I force (or fake) the UserControl to draw its background transparent?
This is what I have set in the contructor of my UserControl:
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = Color.Transparent;
this.DoubleBuffered = true;
I have a potential solution that may work, although I would need more information on how your animated controls work to be sure. There is one unfortunate side effect in my solution, and that is that the DoubleBuffering property only works correctly in .NET control containers. When hosted in MFC, your controls will flicker on resize and other similar display-tearing refreshes. This may cause issues with animated controls, depending on how they are performing drawing work.
To start, I first looked for issues when hosting a .NET UserControl in MFC. After quite a while of reading through the instantiation code of CWinFormsControl::CreateControl() and everything beneath, nothing out of the ordinary came up. In fact, aside from the quirks of loading managed references, the code is identical to how transparent ActiveX controls are loaded.
After learning that piece of information, I used Spy++ to look at whether the .NET control is instantiated with a windowed container. Indeed, it is. After a rather lengthy investigation, this control container appears to be controlled by an instance of a utility class, System.Windows.Forms.Control.AxSourcingSite, which has no documentation and almost no visibility. This was a little bit surprising to me, as usually it is the reverse. MFC and the lesser used WTL have great support for in-place activation, and usually controls can work with whatever the host has setup, whether windowed or not.
From here, I checked on whether this same container exists when the .NET control is hosted in a .NET control container. I assumed that perhaps the control would have its own window, without any special adapters. Turns out, I was wrong. The control works the same way as in-place non-windowed controls. This means that in order to preserve behavior, a solution must allow the regular .NET activation to proceed as normal, and when windowed, it should do something else.
A close look at the MFC hosted version reveals an off-white background drawn in by the .NET UserControl. After more spading and testing, this off-white background is definitely drawn in by a hidden layer in the window message handling chain. This means we can hack together a solution by using AllPaintingInWmPaint.
To demonstrate this, here is the source code for a UserControl that can be hosted in both .NET and the MFC managed container. This control relies on the following things to work around the transparency issues.
Add a member variable, m_ReroutePaint, to allow us to know when we need to override the default WM_PAINT behavior.
Override base.CreateParams and add the WS_EX_TRANSPARENT flag. When this property is called, set m_ReroutePaint to true. This property was not called when the Control is activated in a .NET container.
Override the WndProc() method, and patch up WM_PAINT to our liking if we are rerouting painting activities.
Use BeginPaint()/EndPaint() via Interop to setup/teardown WM_PAINT. Use the provided HDC as the initializer for a Graphics object.
Here are some caveats:
The background color of the control cannot be changed through the BackColor .NET property after the control has been instantiated. One can add workarounds for this, but to keep the sample short and simple, I left out code to do this as the intended goal is for transparent controls. However, if you start with a background color that isn't transparent, the workaround is unnecessary. I did leave code in for this case.
In attaching a HDC to a Graphics object in the WM_PAINT handler via Graphics.FromHdc(), the documentation suggests that Graphics.ReleaseHdc() should be called. However, by doing this, a GDI handle leak occurs. I have left it commented out here, but perhaps someone with GDI+ internals knowledge can figure this out.
This UserControl was created in a project named 'UserCtrlLibrary1'. The DebugPrintStyle() items may be safely removed. Also, handlers were added for resize and paint, which are both in a separate designer file, but trivial to add. AllPaintingInWmPaint should be true through the lifetime of the control.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace UserCtrlLibrary1
{
public partial class CircleControl : UserControl
{
public CircleControl()
{
InitializeComponent();
DebugPrintStyle(ControlStyles.SupportsTransparentBackColor, "initial");
DebugPrintStyle(ControlStyles.AllPaintingInWmPaint, "initial");
DebugPrintStyle(ControlStyles.UserPaint, "initial");
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
DebugPrintStyle(ControlStyles.SupportsTransparentBackColor, "current");
DebugPrintStyle(ControlStyles.AllPaintingInWmPaint, "current");
DebugPrintStyle(ControlStyles.UserPaint, "current");
}
public void DebugPrintStyle(ControlStyles cs, string prefix)
{
Debug.Print("{0}: {1}={2}", prefix, cs.ToString(), this.GetStyle(cs).ToString());
}
bool m_ReroutePaint;
const int WS_EX_TRANSPARENT = 0x0020;
protected override CreateParams CreateParams
{
get
{
if (this.BackColor == Color.Transparent)
{
m_ReroutePaint = true;
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_TRANSPARENT;
return cp;
}
else
{
return base.CreateParams;
}
}
}
private void CircleControl_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
using (SolidBrush b = new SolidBrush(Color.Orange))
{
g.FillEllipse(b, 0, 0, this.Width, this.Height);
}
}
private void CircleControl_Resize(object sender, EventArgs e)
{
this.Invalidate();
}
const int WM_PAINT = 0x000F;
[DllImport("user32.dll")]
static extern IntPtr BeginPaint(IntPtr hwnd, out PAINTSTRUCT lpPaint);
[DllImport("user32.dll")]
static extern bool EndPaint(IntPtr hWnd, [In] ref PAINTSTRUCT lpPaint);
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
struct PAINTSTRUCT
{
public IntPtr hdc;
public bool fErase;
public RECT rcPaint;
public bool fRestore;
public bool fIncUpdate;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] rgbReserved;
}
protected override void WndProc(ref Message m)
{
if ((m.Msg == WM_PAINT) && (m_ReroutePaint))
{
PAINTSTRUCT ps = new PAINTSTRUCT();
BeginPaint(this.Handle, out ps);
using (Graphics g = Graphics.FromHdc(ps.hdc))
{
using (PaintEventArgs e = new PaintEventArgs(g, new Rectangle(ps.rcPaint.Left, ps.rcPaint.Top, ps.rcPaint.Right - ps.rcPaint.Left, ps.rcPaint.Bottom - ps.rcPaint.Top)))
{
this.OnPaint(e);
}
// HACK: This is supposed to be required...
// but it leaks handles when called!
//g.ReleaseHdc(ps.hdc);
}
EndPaint(this.Handle, ref ps);
return;
}
base.WndProc(ref m);
}
}
}
In case anyone other than the OP would like to test this, here are the details to get this up and running in MFC. I created a MFC SDI project, without document-view architecture, with ActiveX control support. This results in generation of typical «project-name» class, ChildView class, and MainFrm classes.
Inside the ChildView.h header, add the following header material before the class (but after #pragma once). Alter the name of the .NET control library if yours is different.
#include <afxwinforms.h>
#using "UserCtrlLibrary1.dll"
using namespace UserCtrlLibrary1;
Add a member variable for the .NET control host. Arbitrarily, I placed mine under the Attributes section.
// Attributes
public:
CWinFormsControl<CircleControl> m_Circle;
Also, I added handlers for OnCreate() and OnSize(). public/protected visibility may be adjusted as you need.
// Generated message map functions
protected:
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
public:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
In ChildView.cpp, I added function bodies for all the items listed above. The message map also needs updates if you didn't use ClassWizard to add the windows message handlers.
BEGIN_MESSAGE_MAP(CChildView, CWnd)
ON_WM_PAINT()
ON_WM_CREATE()
ON_WM_SIZE()
END_MESSAGE_MAP()
void CChildView::OnPaint()
{
CPaintDC dc(this); // device context for painting
RECT rt;
this->GetClientRect(&rt);
rt.right = (rt.right + rt.left)/2;
dc.FillSolidRect(&rt, RGB(0xFF, 0xA0, 0xA0));
}
int CChildView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
RECT rt;
this->GetClientRect(&rt);
m_Circle.CreateManagedControl(WS_VISIBLE, rt, this, 1);
return 0;
}
void CChildView::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
RECT rt;
this->GetClientRect(&rt);
m_Circle.MoveWindow(rt.left, rt.top, rt.right - rt.left, (rt.bottom - rt.top)/2, TRUE);
}
These changes create an instance of the UserControl, and anchor it against the top half of the view. The OnPaint() handler draws a pink band in the left half of the view. Together, transparency should be apparent in the top left quadrant of the view.
To get the MFC project to compile and run, a copy of the UserCtrlLibrary1 output needs to be placed in the same location as the executables for UserCtrlMFCHost. Also, another copy needs to be placed in the same directory as the project source code files for the #using statement. Last, the MFC project should be modified to use the /clr compilation script. In the Configuration Properties section, General subsection, this switch is listed under Project Defaults.
One interesting thing of note, is that this allows the ^ suffix for access to managed classes. At some points in developing this solution, I debated adding methods to be called only when instantiated from MFC, but given that there are ways to detect windowed/non-windowed activation, this wasn't necessary. Other implementations may need this, though, so I feel it is good to point this out.
How to: Compile MFC and ATL code with /clr