如何修复 WPF 表单调整大小 - 控件滞后和黑色背景? [英] How to fix the WPF form resize - controls lagging behind and black background?
问题描述
我有一个非常简单的 WPF 窗口——其中唯一的东西是一个右对齐的按钮.当我通过拖动左边界来调整窗口大小时,按钮会跳来跳去 - 很多.自己试试,来回拖动左边界.
I have a very simple WPF window - the only thing in it is a right-aligned button. When I resize the window by dragging the left boundary, the button jumps around - a lot. Try it yourself, drag the left boundary back and forth.
此外,在调整大小期间,黑色背景会暂时暴露.
Additionally, a black background becomes exposed temporarily during resizes.
在这个问题中,我问了一个关于 Windows 窗体的类似问题.我得到的唯一答案是 WPF 中已修复此问题,但令人惊讶的是,它不仅没有修复,而且 WPF 还添加了第二个视觉错误 - 临时黑色背景.
In this question, I asked a similar question about Windows Forms. The only answer I got suggested that this is fixed in WPF, however, amazingly, not only is it not fixed, but WPF also adds a second visual bug - the temporary black background.
这是控制延迟的样子;当我通过顶部边框调整窗口大小时会发生这种情况(使用相机记录,因为屏幕帽通过使一切变慢而使其不那么明显):
Here's what the control lag looks like; this occurs when I resize the window by its top border (recorded with a camera because screen-cap made it less obvious by making everything slow):
黑色边框示例:这是在调整窗口大小时捕获的;这只是一瞬间,但非常明显:
Example of the black border: this was captured while resizing the window; it's only like this for a split second but it's very noticeable:
我做错了吗?如何在调整大小期间让我的控件在视觉上保持在一个地方?如何避免黑边?
Am I doing something wrong? How can I have my controls stay visually in one place during resizes? How can I avoid the black border?
注意:按钮最终会在正确的位置结束 - 它只会在调整大小期间短暂跳动.
Note: the button ends up in the correct place eventually - it only jumps around briefly during the resize.
推荐答案
这是基于 Wieser Software Ltd 的第二个解决方案的完整工作代码.
This is complete working code based on Wieser Software Ltd's 2nd solution.
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
//ensure win32 handle is created
var handle = new WindowInteropHelper(this).EnsureHandle();
//set window background
var result = SetClassLong(handle, GCL_HBRBACKGROUND, GetSysColorBrush(COLOR_WINDOW));
}
public static IntPtr SetClassLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
{
//check for x64
if (IntPtr.Size > 4)
return SetClassLongPtr64(hWnd, nIndex, dwNewLong);
else
return new IntPtr(SetClassLongPtr32(hWnd, nIndex, unchecked((uint)dwNewLong.ToInt32())));
}
private const int GCL_HBRBACKGROUND = -10;
private const int COLOR_WINDOW = 5;
[DllImport("user32.dll", EntryPoint = "SetClassLong")]
public static extern uint SetClassLongPtr32(IntPtr hWnd, int nIndex, uint dwNewLong);
[DllImport("user32.dll", EntryPoint = "SetClassLongPtr")]
public static extern IntPtr SetClassLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
static extern IntPtr GetSysColorBrush(int nIndex);
}
这篇关于如何修复 WPF 表单调整大小 - 控件滞后和黑色背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!