Найти окно стороннего приложения по заголовку - C#
Формулировка задачи:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace FindWindowByTitle
{
public partial class Form1 : Form
{
[DllImport("USER32.DLL")]
private static extern int GetWindowText(IntPtr IntPtr, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowProc lpEnumFunc, string winName);
public delegate bool EnumWindowProc(IntPtr hWnd, string winName);
public Form1()
{
InitializeComponent();
}
bool FindWindowByTitle(IntPtr hwnd, string winName)
{
StringBuilder str = new StringBuilder(200);
GetWindowText(hwnd, str, 200);
if (!str.ToString().Contains(winName))
return true;
return false;
}
private void Form1_Click(object sender, EventArgs e)
{
Process p= Process.GetProcessesByName("impacthost")[0];
IntPtr hwin = new IntPtr();
hwin = p.MainWindowHandle;
EnumChildWindows(hwin, new EnumWindowProc(FindWindowByTitle), "Gq_MvWorkspace");
}
}
}FindWindowByTitle
правильно находит искомое окно, возвращает false. Но как теперь по выходе изFindWindowByTitle
получить найденный десктиптор? Была надежда, что он будет передан в переменнуюhwin
, но она осталась неизменной. Как тут быть?Решение задачи: «Найти окно стороннего приложения по заголовку»
textual
Листинг программы
using System;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication107
{
public partial class Form1 : Form
{
[DllImport("USER32.DLL")]
private static extern int GetWindowText(IntPtr IntPtr, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowProc lpEnumFunc, WindowFinderInfo winName);
public delegate bool EnumWindowProc(IntPtr hWnd, WindowFinderInfo winName);
public Form1()
{
InitializeComponent();
}
bool FindWindowByTitle(IntPtr hwnd, WindowFinderInfo winName)
{
StringBuilder str = new StringBuilder(200);
GetWindowText(hwnd, str, 200);
if (!str.ToString().Contains(winName.Name))
return true;
winName.Handle = hwnd;
return false;
}
private void button1_Click(object sender, EventArgs e)
{
IntPtr hwin = new IntPtr();
hwin = Process.GetCurrentProcess().MainWindowHandle;
var info = new WindowFinderInfo() { Name = "button1" };
EnumChildWindows(hwin, new EnumWindowProc(FindWindowByTitle), info);
MessageBox.Show(info.Handle == null ? "Пустой хєндл" : info.Handle.ToString());
}
}
public class WindowFinderInfo
{
public string Name;
public IntPtr? Handle;
}
}