[ACCEPTED]-How to open Notepad from a Windows Forms application and place some text in it?-winforms

Accepted answer
Score: 10

The easiest approach is to write a text-file, then 3 open that, rather than the other way round.

You 2 can use System.File.IO.WriteAllText, and the System.Diagnostics.Process class.

A quick code-sample 1 would be along these lines:

File.WriteAllText (
    "This is my letter header\nIt has a new-line in it")
Process.Start("notepad.exe", @"C:\temp\myFile.txt");
Score: 8
  1. Use Process.Start with the property ShellExecute set to true;
  2. Use the clipboard: http://www.dreamincode.net/forums/topic/40011-how-do-i-put-text-in-another-program/


Process.Start returns a Process object which has a MainWindowHandle property. Use 3 that handle when sending text instead of 2 the FindWindow in the above mentioned link.

Update 2

Some 1 code

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
Score: 3

The trick here is to make a text file, and 5 pass it to Notepad as a command line argument, or, if 4 Notepad is the default application for ".txt", you 3 can shell straight to the filename.

Creating/editing textfile through VB.NET

Launch and watch a process from VB.NET 2010

You can 2 use the arguments collection ProcessStartInfo to pass the 1 filename if required.

More Related questions