Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open text in Notepad from .NET?

Tags:

When I click a button on a Windows Forms form, I would like to open a Notepad window containing the text from a TextBox control on the form.

How can I do that?

like image 516
Fire Fist Avatar asked Sep 30 '11 16:09

Fire Fist


People also ask

How do I open text in Notepad?

6. How to start Notepad with a keyboard shortcut. From now on, anytime I want to open Notepad on my computer, all I have to do is press Ctrl + Alt + N.

How do I open Notepad in Visual Studio?

You can open any solution, project, folder or file in Notepad++ by simply right-clicking it in Solution Explorer and select Open in Notepad++.


1 Answers

You don't need to create file with this string. You can use P/Invoke to solve your problem.

Usage of NotepadHelper class:

NotepadHelper.ShowMessage("My message...", "My Title"); 

NotepadHelper class code:

using System; using System.Runtime.InteropServices; using System.Diagnostics;  namespace Notepad {     public static class NotepadHelper     {         [DllImport("user32.dll", EntryPoint = "SetWindowText")]         private static extern int SetWindowText(IntPtr hWnd, string text);          [DllImport("user32.dll", EntryPoint = "FindWindowEx")]         private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);          [DllImport("User32.dll", EntryPoint = "SendMessage")]         private static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);          public static void ShowMessage(string message = null, string title = null)         {             Process notepad = Process.Start(new ProcessStartInfo("notepad.exe"));             if (notepad != null)             {                 notepad.WaitForInputIdle();                  if (!string.IsNullOrEmpty(title))                     SetWindowText(notepad.MainWindowHandle, title);                  if (!string.IsNullOrEmpty(message))                 {                     IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), "Edit", null);                     SendMessage(child, 0x000C, 0, message);                 }             }         }     } } 

References (pinvoke.net and msdn.microsoft.com):

SetWindowText: pinvoke | msdn

FindWindowEx: pinvoke | msdn

SendMessage: pinvoke | msdn

like image 174
kmatyaszek Avatar answered Sep 19 '22 03:09

kmatyaszek