使用 Windows 记事本作为输出控制台
本文关键字:输出 控制台 Windows 记事本 使用 | 更新日期: 2023-09-27 18:33:13
如果有办法将 ascii 输出定向到 Windows 记事本。场景:应用程序启动 Windows 记事本的记事本实例或查找一个记事本实例。比应用程序将一些文本消息推送到记事本,以便消息附加到打开的记事本文本。
Raymond Chen有一个博客,并发表了一篇描述类似内容的帖子,也许你可以根据你想要的来改编它?链接
编辑:来自博客的相关代码
using System;
using System.Diagnostics;
using System.Windows.Automation;
using System.Runtime.InteropServices;
class Program
{
static void Main(string[] args)
{
// Slurp stdin into a string.
var everything = Console.In.ReadToEnd();
// Fire up a brand new Notepad.
var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = @"C:'Windows'System32'notepad.exe";
process.Start();
process.WaitForInputIdle();
// Find the Notepad edit control.
var edit = AutomationElement.FromHandle(process.MainWindowHandle)
.FindFirst(TreeScope.Subtree,
new PropertyCondition(
AutomationElement.ControlTypeProperty,
ControlType.Document));
// Shove the text into that window.
var nativeHandle = new IntPtr((int)edit.GetCurrentPropertyValue(
AutomationElement.NativeWindowHandleProperty));
SendMessage(nativeHandle, WM_SETTEXT, IntPtr.Zero, everything);
}
[DllImport("user32.dll", EntryPoint="SendMessage", CharSet=CharSet.Unicode)]
static extern IntPtr SendMessage(
IntPtr windowHandle, int message, IntPtr wParam, string text);
const int WM_SETTEXT = 0x000C;
}
您可以使用
SendKeys.SendWait
将文本发送到Process
:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SendKeysToProcess
{
class Program
{
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static void Main(string[] args)
{
// Start Notepad process
Process notepad = new Process();
notepad.StartInfo.FileName = @"C:'Windows'Notepad.exe";
notepad.Start();
// Wait for notepad to start
notepad.WaitForInputIdle();
IntPtr p = notepad.MainWindowHandle;
ShowWindow(p, 1);
// Write some text to the Notepad window
SendKeys.SendWait("Hello World!");
}
}
}