国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

2020-01-24 03:26:06
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

            [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,在引用處添加..希望對各位有幫助,也希望能得到各位朋友的指點改進,謝謝

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 都兰县| 大足县| 神农架林区| 虹口区| 云和县| 西平县| 岚皋县| 大厂| 蓬溪县| 和顺县| 西充县| 富裕县| 娱乐| 邵东县| 河津市| 鹤壁市| 大英县| 永善县| 梁山县| 万州区| 吉木萨尔县| 乡宁县| 淮北市| 无棣县| 徐汇区| 曲沃县| 石阡县| 江永县| 青浦区| 城口县| 商都县| 渭南市| 岳阳市| 阿拉善盟| 普定县| 集安市| 崇明县| 华安县| 梅河口市| 辽阳市| 阿巴嘎旗|