2012-07-27 77 views
1

在我的C#winforms應用程序中,我使用Graphics對象來獲取當前的DPI值,以使我的代碼可以縮放某些組件。這工作得很好,除非我一旦調用CreateGraphics(),我的winforms應用程序的外觀和感覺就會改變。風格從熟悉的「圓形」按鈕到更古老的「銳邊」按鈕。爲什麼調用CreateGraphics()會改變我的表單的外觀?

爲什麼會發生這種情況,我該怎麼做才能防止它發生?

我的代碼如下所示:

 Graphics g = this.CreateGraphics(); 
     try 
     { 
      if (g.DpiX == 120.0f) 
      { 
       // scale the components appropriately 
      } 
     } 
     finally 
     { 
      g.Dispose(); 
     } 

其實我可以通過調用的createGraphics,然後立即它處置重現該問題。

任何幫助或洞察力非常感謝!

另一個問題是:是否有無需要創建一個Graphics對象來獲取DPI設置?

回答

0

前段時間,當一位同事開始使用高DPI顯示器時,我正在處理DPI問題。

我的apporach是問桌面,而不是Dpi的特定窗口。當我遇到一些麻煩,我想出了這個代碼(不漂亮,但對我來說相當奏效):

/// <summary> 
    /// Assesses the Systems Primary Monitor's DPI value 
    /// </summary> 
    public static double DPI { 
     get { 
      Graphics g = Graphics.FromHwnd(IntPtr.Zero); 
      IntPtr desktop = g.GetHdc(); 
      int LogicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES); 
      int PhysicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES); 

      float ScreenScalingFactor = (float)PhysicalScreenHeight/(float)LogicalScreenHeight; 

      // dpi1 answers correctly if application is "dpiaware=false" 
      int dpi1 = (int)(96.0 * ScreenScalingFactor); 
      // dpi2 answers correctly if application is "dpiaware=true" 
      int dpi2 = GetDeviceCaps(desktop, (int)DeviceCap.LOGPIXELSX); 

      return Math.Max(dpi1, dpi2); 
     } 
    } 

    [DllImport("gdi32.dll")] 
    static private extern int GetDeviceCaps(IntPtr hdc, int nIndex); 

    private enum DeviceCap { 
     VERTRES = 10, 
     DESKTOPVERTRES = 117, 
     LOGPIXELSX = 88, 

     // http://pinvoke.net/default.aspx/gdi32/GetDeviceCaps.html 
    } 

我特別不喜歡使用Math.Max(dpi1, dpi2)破解,但現在我發現沒有解決方案更好

至於你原來的問題,在Win10上我看不到任何視覺上的變化。對不起,這裏不知道。

相關問題