栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#定位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);
            ///


            /// 定位到txt文件指定行
            ///

            ///文件路径
            ///指定行
            ///定位是否成功
            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,在引用处添加..希望对各位有帮助,也希望能得到各位朋友的指点改进,谢谢

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/127447.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号