I would like to know how to open notepad using C #, with content generated through a string , but I do not want it to be saved anywhere.
I would like to know how to open notepad using C #, with content generated through a string , but I do not want it to be saved anywhere.
For you to open the notepad and write some text in it you need to run the notepad process and then use some Windows functionality.
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);
You will now implement a method that will use this Windows functionality to perform 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);
}
}
Why not create the user's temporary file 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);
}
}