C#定位txt指定行的方法小例子
更新時間:2013年04月24日 15:43:59 作者:
近日,在開發(fā)CAD插件時需要定位TXT文件指定行并將其選中,在網(wǎng)絡(luò)找了一下沒有找到現(xiàn)成的,自己根據(jù)外掛的思路編了一個定位程序,實現(xiàn)了定位功能..與大家分享
復(fù)制代碼 代碼如下:
[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); //等一秒,等文本打開,焦點去到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}");//將光標定位到首行
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");
代碼很簡單,通過FindWindow,FindWindowEx,SetForegroundWindow三個API進行獲取句柄并設(shè)置進程當(dāng)前以及發(fā)送系統(tǒng)命令操作,利用winform中的SendKeys發(fā)送鍵盤命令達到定位的目的.
PS:此命令需要增加 System.Windows.Forms,在引用處添加..希望對各位有幫助,也希望能得到各位朋友的指點改進,謝謝
相關(guān)文章
使用C#調(diào)用系統(tǒng)API實現(xiàn)內(nèi)存注入的代碼
使用C#調(diào)用系統(tǒng)API實現(xiàn)內(nèi)存注入的代碼,學(xué)習(xí)c#的朋友可以參考下。2011-06-06C#實現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法
這篇文章主要介紹了C#實現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法,可實現(xiàn)系統(tǒng)服務(wù)的啟動和停止功能,非常具有實用價值,需要的朋友可以參考下2015-04-04