Skip to content

Instantly share code, notes, and snippets.

@Tocchann
Last active September 16, 2023 08:24
Show Gist options
  • Save Tocchann/aa2d986f795104c4848556df9530872f to your computer and use it in GitHub Desktop.
Save Tocchann/aa2d986f795104c4848556df9530872f to your computer and use it in GitHub Desktop.
WPF で Windows API のオーナーウィンドウとして渡すハンドルを取得する
using System;
using System.Runtime.InteropServices;
using System.Windows;
namespace Tocchann.Interop;
public static class NativeMethods
{
public static IntPtr GetSafeOwnerWindow( Window? ownerWindow )
{
IntPtr hwndOwner = IntPtr.Zero;
if( ownerWindow != null )
{
var hwndSrc = System.Windows.Interop.HwndSource.FromVisual( ownerWindow ) as System.Windows.Interop.HwndSource;
hwndOwner = hwndSrc?.Handle ?? IntPtr.Zero;
}
return NativeMethods.GetSafeOwnerWindow( hwndOwner );
}
public static IntPtr GetSafeOwnerWindow( IntPtr hwndOwner )
{
// 無効なウィンドウを参照している場合の排除
if( hwndOwner != IntPtr.Zero && !IsWindow( hwndOwner ) )
{
hwndOwner = IntPtr.Zero;
}
// オーナーウィンドウの基本を探す
if( hwndOwner == IntPtr.Zero )
{
hwndOwner = GetForegroundWindow();
}
// トップレベルウィンドウを探す
IntPtr hwndParent = hwndOwner;
while( hwndParent != IntPtr.Zero )
{
hwndOwner = hwndParent;
hwndParent = GetParent( hwndOwner );
}
// トップレベルウィンドウに所属する現在アクティブなポップアップ(自分も含む)を取得
if( hwndOwner != IntPtr.Zero )
{
hwndOwner = GetLastActivePopup( hwndOwner );
}
return hwndOwner;
}
// HWND サポート
[DllImport( "user32.dll" )]
[return: MarshalAs( UnmanagedType.Bool )]
public static extern bool IsWindow( IntPtr hWnd );
[DllImport( "user32.dll" )]
public static extern IntPtr GetForegroundWindow();
[DllImport( "user32.dll" )]
public static extern IntPtr GetParent( IntPtr hwnd );
[DllImport( "user32.dll" )]
public static extern IntPtr GetLastActivePopup( IntPtr hwnd );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment