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

Jor*_*dan 4 wpf mfc interop

我在UserControlMFC中托管WPF CWnd.它工作得很漂亮我现在需要弄清楚如何用它的父级调整控件的大小.我已经迷上了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();
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*dan 5

找到了!解决方案是设置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();
}
Run Code Online (Sandbox Code Playgroud)

GetMyControlHwnd在OnCreate主机窗口中调用.该函数通过设置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;
}
Run Code Online (Sandbox Code Playgroud)

当ChildFrame调整大小我简单地改变控制的宽度和高度.

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

    m_myControl->Width = cx;
    m_myControl->Height = cy;
}
Run Code Online (Sandbox Code Playgroud)

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

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

    HWND m_hMyControl;
Run Code Online (Sandbox Code Playgroud)

并且有助于了解这是如何在MFC C++/CLI代码文件中包含CLR命名空间:

using namespace System;
using namespace System::Windows;
using namespace System::Windows::Interop;
Run Code Online (Sandbox Code Playgroud)