110,535
社区成员
发帖
与我相关
我的任务
分享
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);
}
}
}
[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”的空间获取焦点了