如何在C#/ Win32中将文本发送到记事本? [英] How to send text to Notepad in C#/Win32?

查看:160
本文介绍了如何在C#/ Win32中将文本发送到记事本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在记事本中使用SendMessage,以便在不使记事本成为活动窗口的情况下插入书面文本。

I'm trying to use SendMessage to Notepad, so that I can insert written text without making Notepad the active window.

我已经在过去使用 SendText ,但这需要使记事本焦点。

I have done something like this in the past using SendText, but that required giving Notepad focus.

现在,首先,我要获取Windows句柄:

Now, first I'm retrieving the Windows handle:

Process[] processes = Process.GetProcessesByName("notepad");
Console.WriteLine(processes[0].MainWindowHandle.ToString());

我已经确认这是记事本的正确句柄,在中也是如此Windows任务管理器

I've confirmed it's the right handle for Notepad, the same shown within Windows Task Manager.

[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);

从这里开始,我无法使SendMessage在所有实验中都能正常工作。我的方向错误吗?

From here, I haven't been able to get SendMessage to work in all my experimentation. Am I going in the wrong direction?

推荐答案

    [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
    [DllImport("User32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
    private void button1_Click(object sender, EventArgs e)
    {
        Process [] notepads=Process.GetProcessesByName("notepad");
        if(notepads.Length==0)return;            
        if (notepads[0] != null)
        {
            IntPtr child= FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);
            SendMessage(child, 0x000C, 0, textBox1.Text);
        }
    }

WM_SETTEXT = 0x000c

WM_SETTEXT=0x000c

这篇关于如何在C#/ Win32中将文本发送到记事本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆