gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:37:41 29 4
gpt4 key购买 nike

我正在托管 WPF UserControl在 MFC 内 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();
}

最佳答案

Eureka !解决方法是设置HwndSource.SizeToContentSizeToContent.WidthAndHeight .这似乎与 SizeToContent 有悖常理。涉及视口(viewport)根据其包含的大小调整大小的能力,但它起作用了。我的想法是它改变了控件重绘的方式。如果有人想要,整个解决方案如下:

创建并获取 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();
}

调用 GetMyControlHwndOnCreate的主机窗口。该函数通过设置 HwndSource.ParentWindow 自行创建父子关系。属性(property)。
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;
}

我在头文件中有以下私有(private)字段:
// 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;

关于wpf - 如何在 CWnd 中调整 WPF 控件的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18766442/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com