当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现txt定位指定行完整实例

C#实现txt定位指定行完整实例

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#实现txt定位指定行的方法。分享给大家供大家参考。具体实现方法如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.diagnostics;
using system.io;
using system.runtime.interopservices;
namespace wfpapp
{
 class positionnotepad
 {
 [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>  
 public static bool positionnotepad(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);
  //等一秒,等文本打开,焦点去到notepad
  p.waitforinputidle(1000);
  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;
 }
 }
}

调用:

string path = @"c:\users\zkk\desktop\english.txt";
bool res = positionnotepad.positionnotepad(path, "5");

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网