如何更改win32窗口上的文本?

寻找从C#更改win32窗口上的文本的提示,技巧和搜索术语。

更具体地说,我正在尝试将打印对话框上的文本从“打印”更改为“确定”,因为我使用对话框创建打印票而不进行任何打印。

如何找到对话框的窗口句柄? 一旦我得到它,我将如何在窗体的子窗口中找到按钮? 一旦我找到了,我将如何更改按钮上的文字? 如何在显示对话框之前完成所有这些操作?

这里有一个类似的问题,但是它指的是一篇比所需更复杂的CodeProject文章,并且花了我更长的时间来解析,而不是花在这上面。 TIA。

您应该使用Spy ++来查看对话框。 类名很重要,按钮的控件ID也很重要。 如果是本机Windows对话框,则类名应为“#32770”。 在这种情况下,你将在这个post中对我的post有很多用处。 这是C#中的另一个 。 您可以通过P /在按钮手柄上调用SetWindowText()来更改按钮文本。


using System; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; class SetDialogButton : IDisposable { private Timer mTimer = new Timer(); private int mCtlId; private string mText; public SetDialogButton(int ctlId, string txt) { mCtlId = ctlId; mText = txt; mTimer.Interval = 50; mTimer.Enabled = true; mTimer.Tick += (o, e) => findDialog(); } private void findDialog() { // Enumerate windows to find the message box EnumThreadWndProc callback = new EnumThreadWndProc(checkWindow); if (!EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero)) mTimer.Enabled = false; } private bool checkWindow(IntPtr hWnd, IntPtr lp) { // Checks if  is a dialog StringBuilder sb = new StringBuilder(260); GetClassName(hWnd, sb, sb.Capacity); if (sb.ToString() != "#32770") return true; // Got it, get the STATIC control that displays the text IntPtr hCtl = GetDlgItem(hWnd, mCtlId); SetWindowText(hCtl, mText); // Done return true; } public void Dispose() { mTimer.Enabled = false; } // P/Invoke declarations private const int WM_SETFONT = 0x30; private const int WM_GETFONT = 0x31; private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp); [DllImport("user32.dll")] private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp); [DllImport("kernel32.dll")] private static extern int GetCurrentThreadId(); [DllImport("user32.dll")] private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen); [DllImport("user32.dll")] private static extern IntPtr GetDlgItem(IntPtr hWnd, int item); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern bool SetWindowText(IntPtr hWnd, string txt); } 

用法:

  using (new SetDialogButton(1, "Okay")) { printDialog1.ShowDialog(); }