如何在.NET中打开记事本中的文本?

当我单击Windows窗体表单上的按钮时,我想打开一个记事本窗口,其中包含表单上TextBox控件的文本。

我怎样才能做到这一点?

试试这个:

System.IO.File.WriteAllText(@"C:\test.txt", textBox.Text); System.Diagnostics.Process.Start(@"C:\test.txt"); 

您不需要使用此字符串创建文件。 您可以使用P / Invoke来解决您的问题。

NotepadHelper类的用法:

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

NotepadHelper类代码:

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

参考文献(pinvoke.net和msdn.microsoft.com):

SetWindowText: pinvoke | MSDN

FindWindowEx: pinvoke | MSDN

SendMessage: pinvoke | MSDN

使用File.WriteAllText将文件保存到磁盘:

 File.WriteAllText("path to text file", myTextBox.Text); 

然后使用Process.Start在记事本中打开它:

 Process.Start("path to notepad.exe", "path to text file");