欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-18 08:32:28
复制代码 代码如下:            [dllimpor...

复制代码 代码如下:

            [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;
            }


调用代码 locatenotepad("d:\\test.txt","3");

代码很简单,通过findwindow,findwindowex,setforegroundwindow三个api进行获取句柄并设置进程当前以及发送系统命令操作,利用winform中的sendkeys发送键盘命令达到定位的目的.

ps:此命令需要增加 system.windows.forms,在引用处添加..希望对各位有帮助,也希望能得到各位朋友的指点改进,谢谢

上一篇:

下一篇: