C# 创建一个无路径的记事本 并在编辑区添加字符串
C# 创建一个无路径的记事本 并在编辑区添加字符串 调试半天找不到问题所在
- C# code
//引用using System.Runtime.InteropServices;using System.Diagnostics;//在类中声明外部函数 [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)] internal static extern IntPtr GetFocus(); [DllImport("user32.dll", EntryPoint = "FindWindowEx")] internal static extern IntPtr FindWindowEx(IntPtr hWndParent, IntPtr hWndChildAfter, string lpszClass, string lpszWindow); [DllImport("user32.dll",EntryPoint="SendMessageA")] internal static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wparam, string lparam);// 声明消息标识public const int WM_SETTEXT = 0x000C;//在Button_click事件中添加以下代码 Process.Start("Notepad"); IntPtr myNotePad = IntPtr.Zero; myNotePad = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "无标题 - 记事本", null); IntPtr myNote = IntPtr.Zero; myNote = FindWindowEx(myNotePad, IntPtr.Zero, "Edit", null); //SendMessage(myNote, WM_SETTEXT, IntPtr.Zero, strData); SendMessage(myNote, WM_SETTEXT, IntPtr.Zero, "display str");
// 现象是可以打开记事本,但不能添加字符串进去,调试时发现 myNotePad 始终=0,myNote 值是变化的六位数。
[解决办法]
click事件里内容修改如下
- C# code
#region [ 启动记事本 ] System.Diagnostics.Process Proc; try { // 启动记事本 Proc = new System.Diagnostics.Process(); Proc.StartInfo.FileName = "notepad.exe"; Proc.StartInfo.UseShellExecute = false; Proc.StartInfo.RedirectStandardInput = true; Proc.StartInfo.RedirectStandardOutput = true; Proc.Start(); } catch { Proc = null; } #endregion #region [ 传递数据给记事本 ] if (Proc != null) { // 调用 API, 传递数据 while (Proc.MainWindowHandle == IntPtr.Zero) { Proc.Refresh(); } IntPtr vHandle = FindWindowEx(Proc.MainWindowHandle, IntPtr.Zero, "Edit", null); // 传递数据给记事本 SendMessage(vHandle, WM_SETTEXT, IntPtr.Zero, "display str"); } #endregion