从c#代码控制记事本

本文关键字:记事本 控制 代码 | 更新日期: 2023-09-27 18:21:55

我正在从我的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();
            }
    }
    }

有人能告诉我为什么记事本处于活动状态时程序运行不一致吗。

从c#代码控制记事本

您正在使用(至少)两个应用程序-它是您的应用程序和notepad.exe请注意,根据SetForegroundWindow文档,成功使用它有很多限制,例如"当用户使用另一个窗口时,应用程序不能将一个窗口强制设置为前台。相反,Windows会闪烁窗口的任务栏按钮来通知用户。"。"更多相关信息可以在这里找到:如果SetForegroundWindow和ShowWindowAsync不起作用,我如何设置前台窗口?

此外,了解你正在努力实现的目标也会很棒。如果你只想自动化UI,请使用编码的UI测试。。为了只显示文本,请放置一个文本框。