如何从Windows窗体应用程序中打开记事本并在其中放置一些文本?

Sea*_*ean 5 .net vb.net winforms

我正在使用VB.NET和Visual Studio 2008.

我的问题是:如何从Windows窗体应用程序中打开记事本,然后在记事本窗口中放置一些文本字符串?

RB.*_*RB. 10

最简单的方法是编写一个文本文件,然后打开它,而不是相反.

您可以使用System.File.IO.WriteAllTextSystem.Diagnostics.Process类.

快速代码示例将沿着这些方向:

File.WriteAllText (
    @"C:\temp\myFile.txt", 
    "This is my letter header\nIt has a new-line in it")
Process.Start("notepad.exe", @"C:\temp\myFile.txt");
Run Code Online (Sandbox Code Playgroud)


jga*_*fin 8

  1. 使用Process.Start属性ShellExecute设置为true;
  2. 使用剪贴板:http://www.dreamincode.net/forums/topic/40011-how-do-i-put-text-in-another-program/

更新

Process.Start返回一个Process具有MainWindowHandle属性的对象.在上面提到的链接中发送文本而不是FindWindow时使用该句柄.

更新2

一些代码

Const WM_SETTEXT As Integer = &HC
<DllImport("user32.dll")> _
Private Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As IntPtr, <MarshalAs(UnmanagedType.LPStr)> lParam As String) As IntPtr
End Function

Private Shared Sub Main()
    'ProcessStartInfo is used to instruct the Process class
    ' on how to start a new process. The UseShellExecute tells
    ' the process class that it (amongst other) should search for the application
    ' using the PATH environment variable.
    Dim pis As ProcessStartInfo = New ProcessStartInfo("notepad.exe")
    pis.UseShellExecute = True

    ' The process class is used to start the process
    ' it returns an object which can be used to control the started process
    Dim notepad As Process = Process.Start(pis)

    ' SendMessage is used to send the clipboard message to notepad's
    ' main window.
    Dim textToAdd As String = "Text to add"
    SendMessage(notepad.MainWindowHandle, WM_SETTEXT, IntPtr.Zero, textToAdd)
End Sub
Run Code Online (Sandbox Code Playgroud)


Jod*_*ell 5

这里的技巧是创建一个文本文件,并将其作为命令行参数传递给Notepad,或者,如果Notepad是".txt"的默认应用程序,则可以直接使用文件名.

通过VB.NET创建/编辑文本文件

从VB.NET 2010启动并观看流程

ProcessStartInfo如果需要,您可以使用arguments集合来传递文件名.