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

近日,在开发CAD插件时需要定位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;
            }

以上就是C#定位txt指定行的方法小例子的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程