亲宝软件园·资讯

展开

定位txt指定行 C#定位txt指定行的方法小例子

人气:1
想了解C#定位txt指定行的方法小例子的相关内容吗,在本文为您仔细讲解定位txt指定行的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:txt,指定行,下面大家一起来学习吧。

复制代码 代码如下:

            [DllImport("User32.dll", EntryPoint = "FindWindow")]
            private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
            [DllImport("user32.dll")]
            static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
            [DllImport("user32.dll")]
            static extern bool SetForegroundWindow(IntPtr hWnd);
            ///<summary>
            /// 定位到txt文件指定行
            ///</summary>
            ///<param name="strFullName">文件路径</param>
            ///<param name="strRow">指定行</param>
            ///<returns>定位是否成功</returns>
            private bool LocateNotePad(string strFullName, string strRow)
            {
                int iRow;
                int.TryParse(strRow, out iRow);
                if (iRow <= 0)
                {
                    return false;
                }
                IntPtr hwnd = FindWindow("Notepad", string.Format("{0} - 记事本", Path.GetFileName(strFullName)));//查看当前文件是否已打开
                if (hwnd.ToInt32() == 0)
                {
                    Process p = Process.Start(@"notepad.exe",strFullName);
                    p.WaitForInputIdle(1000);  //等一秒,等文本打开,焦点去到notepad
                    System.Windows.Forms.SendKeys.SendWait("{DOWN " + (iRow - 1) + "}");
                    System.Windows.Forms.SendKeys.SendWait("{HOME}"); //行首
                    System.Windows.Forms.SendKeys.SendWait("+{END}"); //选中当前行
                    return true;
                }
                else
                {
                    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Edit", string.Empty);
                    if (hwnd.ToInt32() == 0) return false;
                    else
                    {
                        SetForegroundWindow(hwnd);
                        System.Windows.Forms.SendKeys.SendWait("^{HOME}");//将光标定位到首行
                        System.Windows.Forms.SendKeys.SendWait("{DOWN " + (iRow - 1) + "}"); //
                        System.Windows.Forms.SendKeys.SendWait("{HOME}"); //行首
                        System.Windows.Forms.SendKeys.SendWait("+{END}"); //选中当前行
                    }
                }
                return true;
            }


调用代码 LocateNotePad("D:\\test.txt","3");

代码很简单,通过FindWindow,FindWindowEx,SetForegroundWindow三个API进行获取句柄并设置进程当前以及发送系统命令操作,利用winform中的SendKeys发送键盘命令达到定位的目的.

PS:此命令需要增加 System.Windows.Forms,在引用处添加..希望对各位有帮助,也希望能得到各位朋友的指点改进,谢谢

加载全部内容

相关教程
猜你喜欢
用户评论