c# - 在外部应用程序中设置文本框的文本。 Win32 API

标签 c# winapi interop

使用 Winspector 我发现我想要更改的子文本框的 ID 是 114。为什么这段代码没有更改文本框的文本?

    [DllImport("user32.dll")]
    static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int msg, int Param, string s);

    const int WM_SETTEXT = 0x000c;

    private void SetTextt(IntPtr hWnd, string text)
    {
        IntPtr boxHwnd = GetDlgItem(hWnd, 114);
        SendMessage(boxHwnd, WM_SETTEXT, 0, text);
    }

最佳答案

以下是我为此目的成功使用的内容,其中删除/禁用了我的 GetLastError 错误检查:

[DllImport("user32.dll", SetLastError = false)]
public static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, string lParam);
public const uint WM_SETTEXT = 0x000C;

private void InteropSetText(IntPtr iptrHWndDialog, int iControlID, string strTextToSet)
{
    IntPtr iptrHWndControl = GetDlgItem(iptrHWndDialog, iControlID);
    HandleRef hrefHWndTarget = new HandleRef(null, iptrHWndControl);
    SendMessage(hrefHWndTarget, WM_SETTEXT, IntPtr.Zero, strTextToSet);
}

我已经测试了这段代码并且它有效,所以如果它对你来说失败了,你需要确保你使用了正确的窗口句柄(对话框本身的句柄)和正确的控件 ID。也可以尝试一些简单的操作,例如在记事本中编辑“查找”对话框。

我还不能在帖子中就使用 (char *) 发表评论,但这不是必需的。请参阅 p/Invoke SendMessage 中的第二个 C# 重载.您可以将 String 或 StringBuilder 直接传递给 SendMessage。

我还注意到您说您的控件 ID 是 114。您确定 WinSpector 以 10 为基数给了您这个值吗?因为您将它作为以 10 为底的数字提供给 GetDlgItem。我为此使用 Spy++,它以 16 为基数返回控件 ID。在这种情况下,您将使用:

IntPtr boxHwnd = GetDlgItem(hWnd, 0x0114);

关于c# - 在外部应用程序中设置文本框的文本。 Win32 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1100605/

相关文章:

c# - 如何使用 HttpWebRequest 进行摘要式身份验证?

c# - 静态类的扩展方法?

winapi - Win32 是否支持 FAT 文件系统上的内存映射文件 (CreateFileMapping)?

winapi - 为什么在将 EvtQuery 与 winapi crate 一起使用时会出现 ERROR_INVALID_PARAMETER?

performance - x86 和 x64 中的非托管到托管互操作性能

vba - 为什么我们需要 Application.PathSeparator?

.net - 使用 IDisposable 清理 Excel 互操作对象

c# - Microsoft.Graph GetAsync() 无限期挂起

c# - SVGImage在Mapbox的Unity SDK中导致编译器错误

c++ - 我的代码从另一个进程附加和使用控制台有什么问题?