c#遍历当前所有窗体,获取句柄,然后修改窗体中的值

colincat2004 2009-05-11 03:16:28
问题:如何用C#遍历当前所有打开的窗体,从中找到某一个窗体句柄,通过句柄获取窗体对象,再遍历窗体对象中的控件,找到文本框并修改其中的值。
请高手赐教。
...全文
5437 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
StrongWolf13 2009-09-28
  • 打赏
  • 举报
回复
zgke 2009-05-12
  • 打赏
  • 举报
回复
public delegate bool EnumWindowsProc(IntPtr p_Handle, int p_Param);
[DllImport("user32.dll")]
public static extern int EnumWindows(EnumWindowsProc ewp, int lParam);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, out STRINGBUFFER text, int nMaxCount);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hwnd, ref int lpdwProcessId);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct STRINGBUFFER
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string szText;
}

private void button1_Click(object sender, EventArgs e)
{
MessageWindwos();
}

public void MessageWindwos()
{

EnumWindowsProc _EunmWindows = new EnumWindowsProc(NetEnumWindows);
EnumWindows(_EunmWindows, 0);
}

private bool NetEnumWindows(IntPtr p_Handle, int p_Param)
{
if (!IsWindowVisible(p_Handle))return true;

STRINGBUFFER _TitleString = new STRINGBUFFER();
GetWindowText(p_Handle, out _TitleString, 256);

MessageBox.Show(_TitleString.szText); ///获取的窗体

return true;
}


获取说有窗体 ...获取控件和这个差不过 使用

public delegate bool EnumWindowsProc(IntPtr p_Handle, int p_Param);
[DllImport("user32.dll")]
public static extern int EnumChildWindows(IntPtr hWndParent, EnumWindowsProc ewp, int lParam);
/// <summary>
/// 获取所有控件的信息
/// </summary>
/// <param name="p_Handle">窗体句饼</param>
/// <returns></returns>
public LoadControl(IntPtr p_Handle)
{
EnumWindowsProc _EunmControl = new EnumWindowsProc(NetEnumControl);

Win32API.EnumChildWindows(p_Handle, _EunmControl, 0);
return _ControlList;
}
private bool NetEnumControl(IntPtr p_Handle, int p_Param)
{
STRINGBUFFER _TextString = new STRINGBUFFER();
GetWindowText(p_Handle, out _TextString, 256);


MessageBox.Show(_TextString.szText);

return true;
}

df398286232 2009-05-12
  • 打赏
  • 举报
回复
WindowsAPI 应该要用到的,不过具体怎么用就不清楚了
qqiuzaihui 2009-05-12
  • 打赏
  • 举报
回复
foreach (Form form in Application.OpenForms)
{
foreach (System.Windows.Forms.Control tb in form.Controls)
{
if (tb is TextBox && tb.Name.Equals("控件名称"))
{
tb.Text = "值";
}
}
}

好像相关的窗体及控件均要设置为 public , 楼主自行试试。
colincat2004 2009-05-12
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 yingzhilian2008 的回复:]
Application.OpenForms.GetEnumerator();试试
[/Quote]

这样应该只是可以获取到当前应用程序包含的窗体对象吧?我希望获取系统中运行着的窗体对象
yingzhilian2008 2009-05-11
  • 打赏
  • 举报
回复
Application.OpenForms.GetEnumerator();试试

110,500

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧