如何在CWnd中调整WPF控件的大小?

4

我在一个MFC CWnd中托管了一个WPF UserControl。它的工作非常出色,现在我需要弄清楚如何随着其父控件调整大小。我已经挂钩了OnSize并调用了GetWindowRect,并将结果设置为我的控件,如下所示:

void CChildFrame::OnSize(UINT nType, int cx, int cy)
{
    CRect rect;
    this->GetWindowRect(&rect);

    m_mainControl->Width = rect.Width();
    m_mainControl->Height = rect.Height();
}
1个回答

5
Eureka!解决方案是将 HwndSource.SizeToContent 设置为 SizeToContent.WidthAndHeight。虽然 SizeToContent 与视口能够根据其内容调整大小有关,但这似乎是违反直觉的,但它确实起作用了。我认为它改变了控件重绘的方式。整个解决方案如下:
创建并获取指向WPF用户控件的句柄的函数。 在本例中,名称为 MyControl:
HWND CChildFrame::GetMyControlHwnd(HWND a_parent, int a_x, int a_y, int a_width, int a_height)
{
    HWND mainHandle = AfxGetMainWnd()->GetSafeHwnd();

    IntPtr testHandle = IntPtr(mainHandle);
    HwndSource^ test = HwndSource::FromHwnd(testHandle);

    Global::Bootstrap(IntPtr(mainHandle));

    HwndSourceParameters^ sourceParameters = gcnew HwndSourceParameters("MyControl");

    sourceParameters->PositionX = a_x;
    sourceParameters->PositionY = a_y;
    sourceParameters->Height = a_height;
    sourceParameters->Width = a_width;
    sourceParameters->ParentWindow = IntPtr(a_parent);
    sourceParameters->WindowStyle = WS_VISIBLE | WS_CHILD | WS_MAXIMIZE;

    m_hwndSource = gcnew HwndSource(*sourceParameters);

    m_myControl = gcnew MyControl();

    // *** This is the line that fixed my problem.
    m_hwndSource->SizeToContent = SizeToContent::WidthAndHeight;
    m_hwndSource->RootVisual = m_myControl;

    return (HWND) m_hwndSource->Handle.ToPointer();
}

在宿主窗口的OnCreate中调用GetMyControlHwnd函数。该函数通过设置HwndSource.ParentWindow属性自行创建父子关系。

int CChildFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
    if (CMDIChildWnd::OnCreate(lpCreateStruct) == -1)
        return -1;

    m_hMyControl = GetMyControlHwnd(this->GetSafeHwnd(), 0, 0, lpCreateStruct->cx, lpCreateStruct->cy);

    //// create a view to occupy the client area of the frame
    //if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, 
    //  CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL))
    //{
    //  TRACE0("Failed to create view window\n");
    //  return -1;
    //}

    return 0;
}

ChildFrame调整大小时,我只需更改控件的宽度和高度。

void CChildFrame::OnSize(UINT nType, int cx, int cy)
{
    CRect rect;
    this->GetWindowRect(&rect);

    m_myControl->Width = cx;
    m_myControl->Height = cy;
}

我在头文件中有以下私有字段:

// Fields
private:
    gcroot<HwndSource^> m_hwndSource;
    gcroot<MyControl^> m_myControl;

    HWND m_hMyControl;

了解在MFC C++/CLI代码文件中如何包含CLR命名空间很有帮助:

using namespace System;
using namespace System::Windows;
using namespace System::Windows::Interop;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接