【问题标题】:Controlling notepad from c# code从 C# 代码控制记事本
【发布时间】: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。您不需要执行所有这些“将密钥发送到记事本”业务。只需在您自己的应用程序中放置一个多行文本框即可。

标签: c# .net


【解决方案1】:

您正在使用(至少)两个应用程序 - 它是您的应用程序和 notepad.exe 请注意,根据SetForegroundWindow docs,当您可以成功使用它时有很多限制,例如“当用户正在使用另一个窗口时,应用程序不能将一个窗口强制到前台。相反,Windows 会闪烁窗口的任务栏按钮以通知用户。”更多相关信息可以在这里找到:How can I set a foreground window if SetForegroundWindow and ShowWindowAsync doesn't work?

此外,了解您正在努力实现的目标会很棒。如果您只想自动化 UI,请使用Coded UI tests instead.。对于仅显示文本,托管一个文本框。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    相关资源
    最近更新 更多