用 C# 的Winform程序,.NET平台自带的 Process 和 SendKeys控制记事本程序程序,在指定路径创建文本文件,写入内容并保存。
private void button1_Click( object sender, EventArgs e )
{
//启动notepad.exe 记事本程序,并在d:\下创建 或 打开 text.txt文件
System.Diagnostics.Process txt = System.Diagnostics.Process.Start ( @"notepad.exe", @"d:\text.txt" );
txt.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
//等待一秒,以便目标程序notepad.exe输入状态就绪
txt.WaitForInputIdle ( 1000 );
//如果目标程序 notepad.exe 没有停止响应,则继续
if ( txt.Responding )
{
//开始写入内容
SendKeys.SendWait ( "-----下面的内容是外部程序自动写入-----\r\n" );
SendKeys.SendWait ("写入内容"); //写入内容
SendKeys.SendWait ( "{Enter}{Enter}" ); //写入2个回车
SendKeys.SendWait ( "文档创建时间:" );
SendKeys.SendWait ( "{F5}" ); //发送F5按键
SendKeys.SendWait ("{Enter}"); //发送回车键
SendKeys.SendWait ( "^s" ); //发送 Ctrl + s 键
SendKeys.SendWait ( "%{F4}" ); // 发送 Alt + F4 键
MessageBox.Show ("文件已经保存成功!");
}
}