Csharp/C#教程:C#定位txt指定行的方法小例子分享

代码如下:
           [DllImport(“User32.dll”,EntryPoint=”FindWindow”)]
           privatestaticexternIntPtrFindWindow(stringlpClassName,stringlpWindowName);
           [DllImport(“user32.dll”)]
           staticexternIntPtrFindWindowEx(IntPtrhwndParent,IntPtrhwndChildAfter,stringlpszClass,stringlpszWindow);
           [DllImport(“user32.dll”)]
           staticexternboolSetForegroundWindow(IntPtrhWnd);
           ///<summary>
           ///定位到txt文件指定行
           ///</summary>
           ///<paramname=”strFullName”>文件路径</param>
           ///<paramname=”strRow”>指定行</param>
           ///<returns>定位是否成功</returns>
           privateboolLocateNotePad(stringstrFullName,stringstrRow)
           {
               intiRow;
               int.TryParse(strRow,outiRow);
               if(iRow<=0)
               {
                   returnfalse;
               }
               IntPtrhwnd=FindWindow(“Notepad”,string.Format(“{0}-记事本”,Path.GetFileName(strFullName)));//查看当前文件是否已打开
               if(hwnd.ToInt32()==0)
               {
                   Processp=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}”);//选中当前行
                   returntrue;
               }
               else
               {
     &nbs p;             hwnd=FindWindowEx(hwnd,IntPtr.Zero,”Edit”,string.Empty);
                   if(hwnd.ToInt32()==0)returnfalse;
                   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}”);//选中当前行
                   }
               }
               returntrue;
           }

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

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

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

您可能感兴趣的文章:C#逐行读取txt文件的方法C#操作txt文件,进行清空添加操作的小例子C#实现把txt文本数据快速读取到excel中C#处理文本文件TXT实例详解C#读写txt文件多种方法实例代码c#.NET写txt文件小例子c#数据库与TXT导入导出的实例C#实现EXCEL数据到TXT文档的转换c#读取文件内容存放到int数组array.txtC#实现txt定位指定行完整实例

标签: 定位 方法

MFC命名规则汇总

VC中SDK与MFC的区别浅析

上述就是C#学习教程:C#定位txt指定行的方法小例子分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/904588.html

(0)
上一篇 2021年10月21日
下一篇 2021年10月21日

精彩推荐