0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#でスクリーン解像度を得る

Last updated at Posted at 2021-10-30

はじめに

拡大縮小の設定をしていると正しい解像度が取れなかったのでメモ。
4kモニタとかだと100%でないことの方が多いのでハマりがち。

基本

Forms.Screen.PrimaryScreen.Bounds から取得できる。
マルチディスプレイなら Forms.Screen.AllScreens に各ディスプレイの値が入っている。
ただ、拡大縮小設定を、たとえば200%にしていると、半分の値になってしまう。

どうするか

2つ方法がある。(意味的には同じことをやっている)

  1. SetProcessDPIAwareを呼び出す
  2. マニフェストファイルに <dpiAware>true</dpiAware> を追加する

具体的に

SetProcessDPIAwareはNative methodなので、宣言を追加する必要あり。
以下のようにする。

import System.Runtime.InteropServices;

   .
   .
   .

public Form1()
{
    NativeMethods.SetProcessDPIAware(); // 最初に呼び出す
    InitializeComponent();
}

   .
   .
   .

static class NativeMethods
{
    [DllImport("user32.dll")]
    public static extern bool SetProcessDPIAware();
}


NativeMethods に入れるのは、
https://docs.microsoft.com/ja-jp/dotnet/fundamentals/code-analysis/quality-rules/ca1060
とかを参照。

マニフェストファイルの方は、ソリューションエクスプローラから新しい項目の追加⇨アプリケーション マニフェスト ファイルでapp.manifestを追加し、コメントになっている

  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
  </application>

のところを生かす。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?