アプリ起動時にウインドウを前回終了時の位置に表示する場合、 マルチディスプレイの一方が未接続だとにウインドウがスクリーンの表示範囲外に出てしまうことがある。その場合、メインディスプレイに表示させるようにする。
1. スクリーンサイズを取得するために using System.Windows.Forms を有効にする。
プロジェクトをダブルクリック
csprojのXMLの<PropertyGroup>に次の行を追加
<UseWindowsForms>true</UseWindowsForms>
これだけだと全てのクラスに暗黙的に using System.Windows.Forms が適用され、MessageBoxのライブラリ間の競合が発生する。
'MessageBox' は、'System.Windows.Forms.MessageBox' と 'System.Windows.MessageBox' 間のあいまいな参照ですこれを避けるため、csproj次の設定を追加する。<ItemGroup> <!-- WinFormsの自動usingから、衝突の原因になるSystem.Windows.Formsを削除 --> <Using Remove="System.Windows.Forms" /> </ItemGroup>スクリーンサイズを扱うクラスに using を追加。using WinForms = System.Windows.Forms;2. ウィンドウがスクリーンに表示されているかの判断
//Windowの矩形領域
var windowRect = new Rectangle(Left, Top, Width, Height);bool isVisible = false;foreach (var screen in System.Windows.Forms.Screen.AllScreens)
{
// IntersectsWith を使い、現在のディスプレイの有効範囲(WorkingArea)と
// ウィンドウの矩形領域が重なっているか判定if (screen.WorkingArea.IntersectsWith(windowRect)){isVisible = true;break;}}// どのディスプレイの範囲内にも入っていない、メインディスプレイの左上に配置、または画面右上あたりへ
if (!isVisible)
{this.Left = 100;this.Top = 100;}
0 件のコメント:
コメントを投稿