检测另一个进程中的特定窗口何时打开或关闭

Joh*_*rar 4 .net c# winforms

因此,我制作了一个Win应用程序,我希望每当我打开记事本中的“页面设置”并在我关闭记事本时将其关闭时,它都在屏幕前弹出。

我尝试了这个:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
public static extern IntPtr GetParent(IntPtr hWnd);

[DllImport("User32", CharSet = CharSet.Auto)]
public static extern int ShowWindow(IntPtr hWnd, int cmdShow);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsIconic(IntPtr hwnd);

[DllImport("user32.dll")]

public static extern int SetForegroundWindow(IntPtr hWnd);
ManagementEventWatcher watcher;
public Form1()
{
    InitializeComponent();

    var query = new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = 'Notepad.exe'");
    var mew = new ManagementEventWatcher(query) { Query = query };
    mew.EventArrived += (sender, args) => { AppStarted(); };
    mew.Start();                       
}
protected override void OnLoad(EventArgs e)
{     
    base.OnLoad(e);
    watcher = new ManagementEventWatcher("Select * From Win32_ProcessStopTrace");
    watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
    watcher.Start();
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
    watcher.Stop();
    watcher.Dispose();
    base.OnFormClosed(e);
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    // var _windowHandle = FindWindow(null, "Page Setup");
    if ((string)e.NewEvent["ProcessName"] == "notepad.exe")

    {
        Invoke((MethodInvoker)delegate
     {
         TopMost = false;
         Location = new System.Drawing.Point(1000, 1);
     });

    }

}
async void AppStarted()
{         
    await Task.Delay(300);
    BeginInvoke(new System.Action(PoPInFront));
}
void PoPInFront()
{
    var _notepadProcess = Process.GetProcesses().Where(x => x.ProcessName.ToLower().Contains("notepad")).DefaultIfEmpty(null).FirstOrDefault();
    if (_notepadProcess != null)
    {
        var _windowHandle = FindWindow(null, "Page Setup");
        var _parent = GetParent(_windowHandle);
        if (_parent == _notepadProcess.MainWindowHandle)
        {
            Invoke((MethodInvoker)delegate
            {
                Location = new System.Drawing.Point(550, 330);
                TopMost = true;
            });
        }
    }

    //var ExternalApplication = Process.GetProcessesByName("Notepad").FirstOrDefault(p => p.MainWindowTitle.Contains("Page Setup"));     
    //Location = new System.Drawing.Point(550, 330);
    //TopMost = true;
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我的应用程序会在屏幕前弹出并TopMost = true在我打开记事本时设置,而不是在记事本的“页面设置”中设置,并且在我关闭记事本时它会移回屏幕的一角。

我要做的就是:

我想将应用程序移动到屏幕中央,并在TopMost = true每次打开“页面设置”时将其设置并返回到角落,以及TopMost = false 在“页面设置”关闭时进行设置。

Location = new System.Drawing.Point(550, 330); -屏幕中央

Location = new System.Drawing.Point(1000, 1); -角落

编辑:

我也尝试过这个,但是没有运气。

void PoPInFront()
        {
            //IntPtr hWnd = IntPtr.Zero;
            //foreach (Process pList in Process.GetProcesses())
            //{
            //    if (pList.MainWindowTitle.Contains("Page Setup"))
            //    {
            //        hWnd = pList.MainWindowHandle;
            //        Location = new System.Drawing.Point(550, 330);
            //        TopMost = true;
            //    }
            //}

            var ExternalApplication = Process.GetProcessesByName("Notepad").FirstOrDefault(p => p.MainWindowTitle.Contains("Page Setup"));     
            Location = new System.Drawing.Point(550, 330);
            TopMost = true;
        }
Run Code Online (Sandbox Code Playgroud)

编辑2:

我认为问题出在这里,我不知道该怎么做:

var query = new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = 'Notepad.exe' AND MainWindowTitle = 'Page Setup'");
Run Code Online (Sandbox Code Playgroud)

AND MainWindowTitle = 'Page Setup'

Rez*_*aei 5

您可以使用以下任一选项:

  • 使用SetWinEventHook方法
  • 处理UI自动化事件(首选)(由Hans建议在注释中

解决方案1-使用SetWinEventHook方法

使用,SetWinEventHook您可以侦听其他进程中的某些事件,并注册一个WinEventProc回调方法以在事件引发时接收事件。

这里EVENT_SYSTEM_FOREGROUND可以帮助我们。

我们限制事件接收器从特定进程接收此事件,然后检查导致事件的窗口文本是否等于,Page Setup然后我们可以说Page Setup目标进程中的窗口已打开,否则我们可以告诉Page Setup对话框是没开。

为了使示例更简单,我假设notepad您的应用程序启动时实例是打开的,但是您也可以Win32_ProcessStartTrace用来检测notepad应用程序何时运行。

更具体地说,说出关闭对话框时,您可以侦听EVENT_OBJECT_DESTROY并检测消息是否针对我们感兴趣的窗口。

public const uint EVENT_SYSTEM_FOREGROUND = 0x0003;
public const uint EVENT_OBJECT_DESTROY = 0x8001;
public const uint WINEVENT_OUTOFCONTEXT = 0;
public delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
    int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll")]
public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr
    hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess,
    uint idThread, uint dwFlags);
[DllImport("user32.dll")]
public static extern bool UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
Run Code Online (Sandbox Code Playgroud)
IntPtr hook = IntPtr.Zero;
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    var p = System.Diagnostics.Process.GetProcessesByName("notepad").FirstOrDefault();
    if (p != null)
        hook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND,
        IntPtr.Zero, new WinEventDelegate(WinEventProc), 
        (uint)p.Id, 0, WINEVENT_OUTOFCONTEXT);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
    UnhookWinEvent(hook);
    base.OnFormClosing(e);
}
void WinEventProc(IntPtr hWinEventHook, uint eventType,
    IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
    string s = "Page Setup";
    StringBuilder sb = new StringBuilder(s.Length + 1);
    GetWindowText(hwnd, sb, sb.Capacity);
    if (sb.ToString() == s)
        this.Text = "Page Setup is Open";
    else
        this.Text = "Page Setup is not open";
}
Run Code Online (Sandbox Code Playgroud)

解决方案2-处理UI自动化事件

正如Hans的评论所建议的那样,您可以使用UI Automation API来订阅WindowOpenedEventWindowClosedEvent

在下面的示例中,我认为存在一个打开的实例,notepad并检测到其Page Setup对话框的打开和关闭:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    var notepad = System.Diagnostics.Process.GetProcessesByName("notepad")
                        .FirstOrDefault();
    if (notepad != null)
    {
        var notepadMainWindow = notepad.MainWindowHandle;
        var notepadElement = AutomationElement.FromHandle(notepadMainWindow);
        Automation.AddAutomationEventHandler(
            WindowPattern.WindowOpenedEvent, notepadElement,
            TreeScope.Subtree, (s1, e1) =>
            {
                var element = s1 as AutomationElement;
                if (element.Current.Name == "Page Setup")
                {
                    //Page setup opened.
                    this.Invoke(new Action(() =>
                    {
                        this.Text = "Page Setup Opened";
                    }));
                    Automation.AddAutomationEventHandler(
                        WindowPattern.WindowClosedEvent, element,
                        TreeScope.Subtree, (s2, e2) =>
                        {
                            //Page setup closed.
                            this.Invoke(new Action(() =>
                            {
                                this.Text = "Closed";
                            }));
                        });
                }
            });
    }
}
Run Code Online (Sandbox Code Playgroud)
protected override void OnFormClosing(FormClosingEventArgs e)
{
    Automation.RemoveAllEventHandlers();
    base.OnFormClosing(e);
}
Run Code Online (Sandbox Code Playgroud)

不要忘记添加对UIAutomationClientUIAutomationTypes程序集的引用并添加using System.Windows.Automation;