打开记事本并添加文本不起作用 [英] Open Notepad and add Text not working

查看:114
本文介绍了打开记事本并添加文本不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从互联网上看到了此片段,但对我来说却无效。
应该打开一个新的记事本应用程序,并在其中添加 asdf。

I just saw this snippet from the internet but it doesn't work from me. It's suppose to open a new notepad application and add "asdf" into it.

代码是否有错误?

[DllImport("User32.dll")]     
        public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);

void Test()
{
         const int WM_SETTEXT = 0x000C;

    ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe");
    startInfo.UseShellExecute = false;
    Process notepad = System.Diagnostics.Process.Start(startInfo);
    SendMessage(notepad.MainWindowHandle, WM_SETTEXT, 0, "asdf");
}


推荐答案

要确保该过程是准备接受输入,请调用 notepad.WaitForInputIdle()。而且重要的是使用刚刚创建的进程的 MainWindowHandle 而不是任何记事本进程。

To make sure that process is ready to accept input, call notepad.WaitForInputIdle(). And it is important to use MainWindowHandle of the process that was just created, not the any notepad process.

[DllImport("user32.dll")]
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);

static void ExportToNotepad(string text)
{
    ProcessStartInfo startInfo = new ProcessStartInfo("notepad");
    startInfo.UseShellExecute = false;

    Process notepad = Process.Start(startInfo);
    notepad.WaitForInputIdle();

    IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), null, null);
    SendMessage(child, 0x000c, 0, text);
}

这篇关于打开记事本并添加文本不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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