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);
            ///
            /// 定位到txt文件指定行
            ///

            ///文件路径
            ///指定行
            ///定位是否成功
            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,在引用处添加..希望对各位有帮助,也希望能得到各位朋友的指点改进,谢谢

你可能感兴趣的:(C#定位txt指定行的方法小例子)