要实现WinForm获取当前名称实例的功能,我们可以使用以下步骤:
1.使用System.Diagnostics.Process类获取当前正在运行的所有进程。
using System.Diagnostics;
Process[] processes = Process.GetProcesses();
2.使用LINQ查询找到我们需要的进程实例。
Process process =
processes.FirstOrDefault(p => p.ProcessName.Equals("YourProcessName"));
3.使用process.MainWindowHandle获取该进程的主窗口句柄。
IntPtr hWnd = process.MainWindowHandle;
4.使用Win32 API获取该句柄对应窗口的标题名称。
string windowTitle = string.Empty;
int maxLength = 256;
StringBuilder sb = new StringBuilder(maxLength);
if (GetWindowText(hWnd, sb, maxLength) > 0)
{
windowTitle = sb.ToString();
}
完整代码如下,其中包含了两个示例:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
public class WinFormUtils
{
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
public static string GetActiveWindowName()
{
Process[] processes = Process.GetProcesses();
Process process = processes.FirstOrDefault(p => p.ProcessName.Equals("YourProcessName"));
if (process != null)
{
IntPtr hWnd = process.MainWindowHandle;
if (hWnd != IntPtr.Zero)
{
string windowTitle = string.Empty;
int maxLength = 256;
StringBuilder sb = new StringBuilder(maxLength);
if (GetWindowText(hWnd, sb, maxLength) > 0)
{
windowTitle = sb.ToString();
}
return windowTitle;
}
}
return string.Empty;
}
}
// 示例1:获取当前活动窗口的名称
private void btnGetActiveWindowName_Click(object sender, EventArgs e)
{
string name = WinFormUtils.GetActiveWindowName();
MessageBox.Show(
$"Active window name: {name}",
"Result",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
// 示例2:获取指定进程的窗口名称
private void btnGetProcessWindowName_Click(object sender, EventArgs e)
{
Process[] processes = Process.GetProcesses();
string processName = "notepad";
Process process = processes.FirstOrDefault(p => p.ProcessName.Equals(processName));
if (process != null)
{
IntPtr hWnd = process.MainWindowHandle;
if (hWnd != IntPtr.Zero)
{
string windowTitle = string.Empty;
int maxLength = 256;
StringBuilder sb = new StringBuilder(maxLength);
if (GetWindowText(hWnd, sb, maxLength) > 0)
{
windowTitle = sb.ToString();
}
MessageBox.Show(
$"Window name of {processName}: {windowTitle}",
"Result",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show(
$"Process {processName} does not have a main window",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
以上就是WinForm获取当前名称实例汇总的完整攻略和两个示例说明。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:winform获取当前名称实例汇总 - Python技术站