開いているすべてのプロセスのPIDを表示するためにWindowsタスクマネージャを開くと、Chromeブラウザの開いているすべてのタブに独自のPIDがあることがわかります。使用時のフォーカス:C#外部ブラウザの各ブラウザタブに固有のPIDを取得するにはどうすればいいですか? Chrome/Firefox/IE
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
IntPtr hwnd = GetForegroundWindow();
GetWindowThreadProcessId(hwnd, out pid);
ブラウザのタブを一意に識別する方法を知っている人はいますか?さらに、ブラウザのタブが状態やフォーカスを変更したときにイベントをキャッチする方法を知っている人はいますか?
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace focusWindow2
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern IntPtr SetWinEventHook(SystemEvents eventMin, SystemEvents eventMax, IntPtr hmodWinEventProc,
SystemEventHandler lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
delegate void SystemEventHandler(IntPtr hWinEventHook, SystemEvents @event, IntPtr hwnd, int idObject, int idChild,
uint dwEventThread, uint dwmsEventTime);
enum SystemEvents
{
ForegroundWindowChanged = 0x3 // EVENT_SYSTEM_FOREGROUND - The only flag we care about
}
IntPtr _WinEventHook;
SystemEventHandler _WinEventHookHandler;
public Form1()
{
InitializeComponent();
// Create the handler
_WinEventHookHandler = new SystemEventHandler(WinEventHook);
// Set the hook
_WinEventHook = SetWinEventHook(SystemEvents.ForegroundWindowChanged, SystemEvents.ForegroundWindowChanged,
IntPtr.Zero, _WinEventHookHandler, 0, 0, 0);
this.FormClosing += delegate
{
UnhookWinEvent(_WinEventHook);
};
}
private void WinEventHook(IntPtr hWinEventHook, SystemEvents @event, IntPtr hwnd, int idObject, int idChild,
uint dwEventThread, uint dwmsEventTime)
{
uint pid = 0;
GetWindowThreadProcessId(hwnd, out pid);
Process p = Process.GetProcessById((int)pid);
string procName = Path.GetFileName(p.ProcessName);
textBox1.Text += procName + " " + pid + "\r\n";
}
}
}
私が知っている唯一のブラウザは、タブごとに異なるプロセスを実際に使用しているブラウザです。ほとんどのブラウザは複数のスレッドを使用します。あなたが常にGetForegroundWindow()から同じプロセスを取得する理由は、開いているタブのプロセスではなく、メインのクロムプロセスを返すためです。 – firthh
@firthh:IE9もマルチプロセスです。 –
IE9には複数のプロセスがありますが、タブごとに1つのプロセスは使用されません。パフォーマンス上の理由から、プロセスごとに複数のタブをホストします。 – snemarch