2011-09-30 66 views

回答

35

尝试了这一点:

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

是的,不要强制使用具有自己喜欢的文本编辑器的用户的记事本。 –

+0

我从你那里得到了答案。谢谢。 :) –

+1

如果不止一次使用,那么文件会覆盖自身,所以它不会像继续制作新副本一样导致垃圾堆积。在系统临时文件夹中创建路径。 –

6

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

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

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

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

非常感谢您的回答。 :) –

+0

@碎片 - 我不明白你的问题。当文件在记事本中打开时,它将被锁定。 – Oded

+0

当我这样写你的答案。 string s = txtNum.Text; Process.Start(“notepad.exe”,s); 该文本只出现header.not在记事本中打开。 我错了吗? –

32

你不需要用这个字符串创建文件。您可以使用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

+2

这是更干净的做事方式。不要将垃圾数据留在磁盘上。 – Oybek

+0

@kmatyaszek看起来您的参考链接已损坏,或者网站已关闭?如果可能,你介意更新它们吗? –

+0

@Shredder网站pinvoke.net是在线,但我也添加了对msdn网站的引用。 – kmatyaszek

相关问题