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);
///<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)));//查看當(dāng)前文件是否已打開
if (hwnd.ToInt32() == 0)
{
Process p = Process.Start(@"notepad.exe",strFullName);
p.WaitForInputIdle(1000); //等一秒,等文本打開,焦點(diǎn)去到notepad
System.Windows.Forms.SendKeys.SendWait("{DOWN " + (iRow - 1) + "}");
System.Windows.Forms.SendKeys.SendWait("{HOME}"); //行首
System.Windows.Forms.SendKeys.SendWait("+{END}"); //選中當(dāng)前行
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}");//將光標(biāo)定位到首行
System.Windows.Forms.SendKeys.SendWait("{DOWN " + (iRow - 1) + "}"); //
System.Windows.Forms.SendKeys.SendWait("{HOME}"); //行首
System.Windows.Forms.SendKeys.SendWait("+{END}"); //選中當(dāng)前行
}
}
return true;
}
調(diào)用代碼 LocateNotePad("D:\\test.txt","3");
代碼很簡(jiǎn)單,通過FindWindow,FindWindowEx,SetForegroundWindow三個(gè)API進(jìn)行獲取句柄并設(shè)置進(jìn)程當(dāng)前以及發(fā)送系統(tǒng)命令操作,利用winform中的SendKeys發(fā)送鍵盤命令達(dá)到定位的目的.
PS:此命令需要增加 System.Windows.Forms,在引用處添加..希望對(duì)各位有幫助,也希望能得到各位朋友的指點(diǎn)改進(jìn),謝謝
- C#逐行讀取txt文件的方法
- C#操作txt文件,進(jìn)行清空添加操作的小例子
- C#實(shí)現(xiàn)把txt文本數(shù)據(jù)快速讀取到excel中
- C#處理文本文件TXT實(shí)例詳解
- C#讀寫txt文件多種方法實(shí)例代碼
- c#.NET 寫txt文件小例子
- c#數(shù)據(jù)庫(kù)與TXT導(dǎo)入導(dǎo)出的實(shí)例
- C#實(shí)現(xiàn)EXCEL數(shù)據(jù)到TXT文檔的轉(zhuǎn)換
- c# 讀取文件內(nèi)容存放到int數(shù)組 array.txt
- C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
相關(guān)文章
使用C#調(diào)用系統(tǒng)API實(shí)現(xiàn)內(nèi)存注入的代碼
使用C#調(diào)用系統(tǒng)API實(shí)現(xiàn)內(nèi)存注入的代碼,學(xué)習(xí)c#的朋友可以參考下。2011-06-06C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法,可實(shí)現(xiàn)系統(tǒng)服務(wù)的啟動(dòng)和停止功能,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04