以下のコードは次のことを行います
PushWindowToFront():
- 後で参照するために現在のプロセス ID を取得します
- コールバックEnumWindowsCallbackメソッドでuser32.dll 関数EnumWindowsを呼び出します
- 次に、EnumWindows は各ウィンドウを反復処理し、それぞれのコールバックを呼び出します
折り返し電話:
- ウィンドウ スレッドのプロセス ID が現在のプロセス ID と同じかどうかを確認します
- その場合は、ウィンドウのテキストが「選択」で始まるかどうかを確認します
- その場合は、ウィンドウ ハンドルで user32.dll 関数 SetFocus を呼び出します。
- 最後の win32 エラーを確認して印刷する
ただし、常に win32 エラー 5 - 「アクセスが拒否されました」が返されます。同じプロセスに属するウィンドウに対してアプリケーションがこの関数を呼び出すことができないのはなぜですか?
.
public void PushWindowToFront()
{
currentProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;
Win32Methods.EnumWindowsCallbackDelegate callback = new Win32Methods.EnumWindowsCallbackDelegate(this.EnumWindowsCallback);
Win32Methods.EnumWindows(callback, (IntPtr) 0);
}
public bool EnumWindowsCallback(IntPtr hWnd, IntPtr lParam)
{
uint i = 0;
Win32Methods.GetWindowThreadProcessId(hWnd, out i);
if (currentProcessId == i)
{
StringBuilder sb = new StringBuilder(512);
Win32Methods.GetWindowText(hWnd, sb, sb.Capacity);
if (sb.ToString().Split(' ')[0].ToLower().Equals("select"))
{
IntPtr result = Win32Methods.SetFocus(hWnd);
Console.WriteLine("Window found: {0}\r\nSetting focus...\r\nResult: {1}\r\nLastError: {2}",
sb.ToString(), result, Marshal.GetLastWin32Error().ToString());
}
}
return true;
}