【发布时间】:2012-02-28 15:44:47
【问题描述】:
我正在从我的 c# 代码向记事本发送 %FO、^V、%O 之类的击键。 我编写了代码来处理这两种情况,例如记事本是否处于活动状态。 对于活动记事本,我只是获取它的句柄并将前景窗口设置为记事本。
代码适用于非活动记事本,但对于活动部分,它会运行一段时间或有时会失败,即不一致。
Following is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string keys = "";
string path;
int iHandle;
iHandle = NativeWin32.FindWindow(null, "Untitled - Notepad");
//acquiring handle of notepad(active)
if (iHandle!=0)
{
NativeWin32.SetForegroundWindow(iHandle);
}//checking whether notepad is active
else
{
Process.Start("notepad");
}//launching notepad when not active
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetNam().CodeBase);
//path of directory
containing file to be
opened and the code
Clipboard.Clear();
Clipboard.SetText(path + "\\Hello.txt");
keys = "%FO";
System.Windows.Forms.SendKeys.SendWait(keys);
keys = "^V";
System.Windows.Forms.SendKeys.SendWait(keys);
keys = "%O";
System.Windows.Forms.SendKeys.SendWait(keys);
Application.Exit();
}
}
}
谁能告诉我为什么当记事本处于活动状态时程序运行不一致。
【问题讨论】:
-
呃,这是实现 UI 自动化的错误方式。正如您已经发现的那样,它非常脆弱。更重要的是,甚至不清楚这是什么意思。对于像记事本这样简单的东西,只需将多行
TextBox控件拖放到表单上会更容易方式,您可以随意控制... -
“或者有时会失败”——非常模糊,请详细说明。
-
等等,轮子不是已经发明了吗? :) 看看
RichTextBox。您不需要执行所有这些“将密钥发送到记事本”业务。只需在您自己的应用程序中放置一个多行文本框即可。