C#FindWindow等相关方法
2015-04-28 08:39:28 访问(3539) 赞(0) 踩(0)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void DO()
{
var hNotePad = FindWindow("Notepad", null);
if (hNotePad == IntPtr.Zero)
throw new Exception("notepad 没有打开");
IntPtr hDialog = IntPtr.Zero;
EnumWindows((hwnd, lParam) =>
{
var owner = GetWindow(hwnd, GW_OWNER);
if (owner == hNotePad)
hDialog = hwnd;
return true;
}, IntPtr.Zero);
if (hDialog == IntPtr.Zero)
throw new Exception("请先打开字体对话框");
var sb = new StringBuilder(250);
GetWindowText(hDialog, sb, 250);
if (sb.ToString() != "字体")
throw new Exception("打开的不是字体对话框");
var hCombobox = GetDlgItem(hDialog, 0x470);
Console.WriteLine("--------- 对话框上的控件列表 --------");
EnumChildWindows(hDialog, (hChild, _) =>
{
var id = GetDlgCtrlID(hChild);
var sb2 = new StringBuilder(250);
GetClassName(hChild, sb, 250);
GetWindowText(hChild, sb2, 250);
Console.WriteLine("0x{0:x} (id = 0x{1:x}) : {2} (\"{3}\")", hChild, id, sb, sb2);
return true;
}, IntPtr.Zero);
var item = "华文中宋";
var index = SendMessage(hCombobox, CB_FINDSTRING, 0, item);
Console.WriteLine("选取'{0}', index={1}", item, index);
SendMessage(hCombobox, CB_SELECTSTRING, 0, item);
}
public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern IntPtr GetWindow(IntPtr hWnd, int uCmd);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll")]
private static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern int GetDlgCtrlID(IntPtr hwndCtl);
[DllImport("user32.dll")]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, int wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, int wParam, string lParam);
private const int GW_OWNER = 4;
private const int CB_FINDSTRING = 0x014C;
private const int CB_SELECTSTRING = 0x014D;
private const int CB_SETCURSEL = 0x014E;
private void button1_Click(object sender, EventArgs e)
{
try
{
DO();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
}
标签:
C#FindWindow等相关方法 


上一条:
下一条:
相关评论
发表评论