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

來源:互聯網
上載者:User

複製代碼 代碼如下: [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,在引用處添加..希望對各位有協助,也希望能得到各位朋友的指點改進,謝謝

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.