How to open the notepad with contents inside without saving?

Asked

Viewed 672 times

1

I would like to know how to open the notepad using C#, with content generated through a string, but I don’t want you to be safe anywhere.

  • 1

    I’m using Visual Studio, I’m new to C#, so I’m using Process.Start("Notepad.exe") to open the note block, but I want the content to appear.

  • 1

    Link tips given by the user @Andersoncarloswoss on network chat, to assess if you have anything that helps https://stackoverflow.com/questions/7613576/ and https://stackoverflow.com/questions/552671/

2 answers

3


To open the Notepad and write some text on it you need to run the process of Notepad and then use some Windows features.

First import these two methods into your class:

using System.Runtime.InteropServices;

[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);

Now you will implement a method that will use this Windows features to run what you want:

public void EscreverNotepad(string texto)
{
    Process.Start("notepad.exe");
    Process[] notepad = Process.GetProcessesByName("notepad");

    if (notepad.Length == 0)
        return;

    if (notepad[0] != null)
    {
        IntPtr child = FindWindowEx(notepad[0].MainWindowHandle, new IntPtr(0), "Edit", null);
        SendMessage(child, 0x000C, 0, texto);
    }        
}

1

Why not create the file in the user’s temporary and then delete it?

private void CreateTempFile()
{
    string strTempFile = $"{Path.GetTempPath()}{Path.GetRandomFileName()}.txt";

    try
    {
        using (StreamWriter sw = new StreamWriter(strTempFile))
            sw.WriteLine("ola mundo");

        Process process = Process.Start(strTempFile);

        // aguardar que o processo conclua o loading
        process.WaitForInputIdle();
        // esperar que o processo feche
        process.WaitForExit();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (File.Exists(strTempFile))
            File.Delete(strTempFile);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.