gpt4 book ai didi

c# - 查找以前关注的应用程序 - WinAPI

转载 作者:行者123 更新时间:2023-11-30 15:49:06 25 4
gpt4 key购买 nike

我在一个相关问题中“回答”了这个问题 - 但它更像是一个我遇到麻烦的附加问题,我需要更新的答案...

基本上我有一个在屏幕上保持打开状态的应用程序,用户可以在进入三个第 3 方应用程序之一后按我的应用程序上的按钮。

当他们单击我的应用程序上的按钮时,我需要确定他们最后使用的三个应用程序中的哪一个,以便知道要与哪个数据库对话。我已经沿着查看 GetForeGroundWindow 和 GetWindow 的路线走,但是我从 GetWindow 获得的窗口句柄总是指一个标题为 M 的窗口。我使用了 Managed Windows API 工具中的 Winternal Explorer 工具,我可以找到 M 句柄返回,它是我所追求的进程的“子进程”——但从这个句柄我无法获得进程名称。

我已经使用简单的 Windows 窗体完成了一个小示例应用程序 - 我启动它然后将记事本设为焦点,然后单击我的按钮并获得句柄 - 但是当查看所有进程的 MainWindowHandle 时,它未列出,但使用 Winternal Explorer 我可以看到它是记事本进程的子进程。

关于为什么我只返回这个子进程句柄而不是实际进程句柄有什么建议吗?

示例代码如下 - 在 Windows XP sp 3 机器上运行

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace TestWindowsAPI
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
IntPtr thisWindow = GetForegroundWindow();
IntPtr lastWindow = GetWindow(thisWindow, 2);

tbThisWindow.Text = thisWindow.ToString();
tbLastWindow.Text = lastWindow.ToString();
}
}
}

最佳答案

您可以使用 GetWindowThreadProcessId从(子)窗口句柄获取进程 ID:

uint lastProcess;
GetWindowThreadProcessId(lastWindow, out lastProcess);

关于c# - 查找以前关注的应用程序 - WinAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2093046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com