[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;
}
代碼很簡單,通過FindWindow,FindWindowEx,SetForegroundWindow三個API進行獲取句柄并設置進程當前以及發送系統命令操作,利用winform中的SendKeys發送鍵盤命令達到定位的目的.