Windows Forms window changes its size when I create a WPF window

后端 未结 3 1337
别跟我提以往
别跟我提以往 2020-12-02 01:46

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

相关标签:
3条回答
  • 2020-12-02 02:18

    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.

    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]
    

    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.

    0 讨论(0)
  • 2020-12-02 02:28

    These is some method you can use. Set the width and height of the window:

    public static Graphics graphics = Graphics.FromHwnd(IntPtr.Zero);
    public static double GetDIPIndependent(double value, double DPI)
    {
        value = value * (graphics.DpiX / DPI);
        return value;
    }
    public static double GetDIPDependent(double value, double DPI)
    {
        value = value * (DPI / graphics.DpiX);
        return value;
    }
    public static double GetDIPIndependent(double value)
    {
        value = value * (graphics.DpiX / 96.0);
        return value;
    }
    
    public static double GetDIPDependent(double value)
    {
        value = value * (96.0 / graphics.DpiX);
        return value;
    }
    

    Example:

    If DPI independent

    this.Width = GetDIPIndependent(this.Width)
    this.Height = GetDIPIndependent(this.Height)
    

    If DPI dependent

    this.Width = GetDIPDependent(this.Width)
    this.Height = GetDIPDependent(this.Height)
    

    It works for me...

    0 讨论(0)
  • 2020-12-02 02:32

    As stated in other replies that is because of the DPI awareness. A quick fix to turn it off for those using VB.NET:

    Open the app.manifest

    And then uncomment this part and set the DPI awareness to false:

    Note that this might cause your application's fonts to look more blurry on higher DPI devices.

    0 讨论(0)
提交回复
热议问题