创建WPF窗口时,Windows窗体窗口会更改其大小 [英] Windows Forms window changes its size when I create a WPF window

查看:211
本文介绍了创建WPF窗口时,Windows窗体窗口会更改其大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 System.Window.Forms.Form ,在这里我处理每次按钮单击。当我收到第一个事件时,我将创建一个新的WPF System.Windows.Window 对象。

I have a System.Window.Forms.Form where I handle every button click. When I receive the first event I create a new WPF System.Windows.Window object.

class WPF_Window : Window
{
}


public partial class Form1 : Form
{
    WPF_Window wnd = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        if (wnd == null)
        {
            wnd = new WPF_Window();
        }
    }
}

在我的计算机上,此代码有效如预期的那样,但是如果我单击Windows窗体窗口时在另一台计算机(都是Windows 10)上运行它,则会更改其大小(减小其尺寸)。

On my computer this code works as expected, but if I run it on another computer (both Windows 10) when I click the Windows Forms window changes its size (decreasing its dimensions).

可能?如何避免这种行为?

How is it possible? How can I avoid this behavior?

推荐答案

您发现WPF调用了SetProcessDPIAware()。它发生在PresentationCore的模块初始化程序中。这在形式上是非法的,必须在应用程序创建任何窗口或加载可能缓存DPI值的DLL之前始终调用它。换句话说,这可能会导致很多错误,但您只是发现了它的温和版本。在纯WPF应用程序中通常不会出现问题,因为PresentationCore始终需要先加载,然后才能创建任何窗口。

You discovered that WPF calls SetProcessDPIAware(). It happens inside the module initializer for PresentationCore. Which is formally illegal, it must always be called before an app creates any windows or load DLLs that might cache the DPI value. Or in other words, lots of ways that this can go wrong, you only discovered the mild version of it as yet. Not normally a problem in a pure WPF app since PresentationCore always needs to be loaded before any window can be created.

他们确实留下了后门以禁用此行为。复制/粘贴此代码,最好在EXE项目的AssemblyInfo.cs源文件中进行:

They did leave a back-door to disable this behavior. Copy/paste this code, best in the AssemblyInfo.cs source file for your EXE project:

   [assembly: System.Windows.Media.DisableDpiAwareness]

但这当然不是真正的解决方案,DPI虚拟化现在始终为所有窗口启用。通过在清单中声明您的应用程序具有dpi意识,从而使PresentationCore避免混乱,取得成功。但是由于不可避免的副作用,您现在会发现需要修复Winforms UI。仅当您更改Form.AutoScaleMode属性或执行诸如硬编码窗口大小之类的不明智操作时,它才会变小。该属性是问题与解答修复程序。

But that isn't much of a true fix of course, DPI virtualization is now always enabled for all of your windows. Get ahead by declaring your app dpi-aware in its manifest so that PresentationCore can't mess this up. But with the inevitable side-effect that you'll now discover that you need to fix your Winforms UI. It can only get smaller when you changed the Form.AutoScaleMode property or do something unwise like hard-coding the window size. The attribute is the Q&D fix.

这篇关于创建WPF窗口时,Windows窗体窗口会更改其大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆