LoginSignup
7
4

More than 1 year has passed since last update.

WinUI3 Desktopでウィンドウのサイズを変更する (Windows App SDK)

Posted at

WinUI3 Desktopでアプリを作ると、ウィンドウのサイズが自動的に決められてしまいます。 Microsoft.UI.Xaml.WindowクラスにはWidthやHeightといったプロパティがありません。

ウィンドウのサイズを指定するには、AppWindowのインスタンスを取得します。

using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using System;
using Windows.Graphics;

public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();

        IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
        WindowId myWndId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
        AppWindow appWindow = AppWindow.GetFromWindowId(myWndId);

        appWindow.Resize(new SizeInt32(800, 600));
    }
}

ウィンドウサイズを指定したいだけなのに、いきなりきな臭いコードです。将来的にはもっと簡単になるんじゃないかと思いますが…。

このコード、packagedなアプリでは動きますが、unpackagedなアプリではTargetInvocationExceptionの例外が出て動きません(Windows App SDK 1.0現在)。app.manifestにsupportedOSを追加することで、unpackagedなアプリでも動作するようになることが知られています。

app.manifest
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="Sample.app"/>

  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <!-- The combination of below two tags have the following effect:
           1) Per-Monitor for >= Windows 10 Anniversary Update
           2) System < Windows 10 Anniversary Update
      -->
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>
      <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
    </windowsSettings>
  </application>
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- Windows 10 -->
      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
    </application>
  </compatibility>
</assembly>

この回避策は、いずれ不要になるものと思われます。

packagedとunpackagedの違いについてはこちらで解説しています。

7
4
2

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
7
4