C#でのウィンドウハンドル(hWnd)
ウィンドウハンドル(hWnd)とは
ウィンドウハンドル(hWnd)は、Windows OSにおいてウィンドウを識別するための一意の識別子(ハンドル)です。これは、Win32 APIにおける「HWND」型の値であり、C#では主にP/Invokeを使用して扱います。
例えば、アプリケーション内の特定のウィンドウを操作したい場合や、他のプロセスのウィンドウを取得する場合に使用されます。
ウィンドウハンドルの取得
ウィンドウハンドルを取得する方法はいくつかあります。
現在のウィンドウのハンドルを取得する
C#のWindows Formsアプリケーションで現在のウィンドウのハンドルを取得するには、this.Handle
を使用します。
using System;
using System.Windows.Forms;
public class MainForm : Form
{
public MainForm()
{
Button btn = new Button { Text = "Get hWnd" };
btn.Click += (s, e) => MessageBox.Show($"hWnd: {this.Handle}");
Controls.Add(btn);
}
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
}
別のウィンドウのハンドルを取得する
FindWindow
を使用すると、他のプロセスのウィンドウハンドルを取得できます。
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
static void Main()
{
IntPtr hWnd = FindWindow(null, "メモ帳");
if (hWnd != IntPtr.Zero)
Console.WriteLine($"メモ帳のウィンドウハンドル: {hWnd}");
else
Console.WriteLine("ウィンドウが見つかりませんでした。");
}
}
ウィンドウハンドルの使用方法
取得したhWndを使用すると、ウィンドウを操作できます。例えば、最前面に表示したり、サイズを変更したりできます。
ウィンドウを最前面にする
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
static void Main()
{
IntPtr hWnd = FindWindow(null, "メモ帳");
if (hWnd != IntPtr.Zero)
SetForegroundWindow(hWnd);
}
}
ウィンドウの操作
ウィンドウを最小化・最大化する
using System;
using System.Runtime.InteropServices;
class Program
{
const int SW_MINIMIZE = 6;
const int SW_MAXIMIZE = 3;
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static void Main()
{
IntPtr hWnd = FindWindow(null, "メモ帳");
if (hWnd != IntPtr.Zero)
{
ShowWindow(hWnd, SW_MAXIMIZE); // 最大化
}
}
}
ウィンドウの位置を変更する
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
static void Main()
{
IntPtr hWnd = FindWindow(null, "メモ帳");
if (hWnd != IntPtr.Zero)
{
MoveWindow(hWnd, 100, 100, 800, 600, true);
}
}
}
サンプルコード
ウィンドウのリストを取得する
using System;
using System.Text;
using System.Runtime.InteropServices;
class Program
{
delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
static bool EnumWindow(IntPtr hWnd, IntPtr lParam)
{
StringBuilder sb = new StringBuilder(256);
GetWindowText(hWnd, sb, sb.Capacity);
if (sb.Length > 0)
Console.WriteLine($"hWnd: {hWnd}, Title: {sb}");
return true;
}
static void Main()
{
EnumWindows(EnumWindow, IntPtr.Zero);
}
}
まとめ
- ウィンドウハンドル(hWnd)は、Windows OS上でウィンドウを識別するための一意の識別子。
FindWindow
やthis.Handle
で取得可能。- P/Invokeを使って、ウィンドウの操作が可能。
- 最前面化、最小化・最大化、位置変更などができる。
ウィンドウ操作をC#で行う場合、Win32 APIを活用することが多く、P/Invokeの理解が重要です。