textbox 光标定位问题

Simeone_xu 2013-06-27 10:32:05
       private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
// openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
openFileDialog.Filter = "文本文件|*.*|C#文件|*.cs|所有文件|*.*";
openFileDialog.RestoreDirectory = true;
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{

textBox1.Text = System.IO.File.ReadAllText(openFileDialog.FileName, Encoding.Default);


}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}



如何在打开文件后 把光标定位到指定的一行 和某个位置 就累世与书签 谢谢大神们
...全文
78 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Kim_Du 2013-06-27
  • 打赏
  • 举报
回复
这完全不看问题内容就回答啊,太不负责了吧

[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);
private bool LocateNotePad(string strFullName, string strRow)//strFullName文件的路径,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;
        }
这是我之前在网上找到的,自己也用过,如果不要选中只要光标定位的话,将选中当前行那一句注释掉就可以了,结合你的代码修改一下应该就可以用了。
  • 打赏
  • 举报
回复
this.TextBox1.Focus();
这样就可以让ID为“TextBox1”的空间获取焦点了

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧