naw*_*fal 9 c# focus process windows-shell winforms
我用我的程序打开了一个记事本,Process.Start()但新打开的记事本覆盖了屏幕.但我确实希望我的应用程序保持其重点.
我同样(使用相同的Process.Start)打开MS Excel和Word,但要将焦点重新放回我的表单,我需要编写的是:
this.Focus();
Run Code Online (Sandbox Code Playgroud)
但是用记事本怪起来:我打开记事本(以及所有其他这样的过程)
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.EnableRaisingEvents = true;
process.StartInfo.FileName = @"abc.log";
process.Start();
Run Code Online (Sandbox Code Playgroud)
现在记事本成为焦点.
我试过这些:
this.Activate(),this.Focus()不用提
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern IntPtr SetFocus(HandleRef hWnd);
{
IntPtr hWnd = myProcess.Handle;
SetFocus(new HandleRef(null, hWnd));
}
Run Code Online (Sandbox Code Playgroud)[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_SHOW = 5;
private const int SW_MINIMIZE = 6;
private const int SW_RESTORE = 9;
{
ShowWindow(Process.GetCurrentProcess().MainWindowHandle, SW_RESTORE);
SetForegroundWindow(Process.GetCurrentProcess().MainWindowHandle);
}
Run Code Online (Sandbox Code Playgroud)另一个更长的解决方案来自这里.
所有这些仍然把重点放在记事本上.为什么仅仅将焦点集中到一个窗口是如此困难,那也是应用程序自己的窗口?
编辑:充其量我可以打开记事本最小化,但它仍然不会在尝试所有上述代码后将焦点放在表单上.记事本打开最小化,但焦点将仍然在记事本(有时我们在Windows XP中看到的东西)和形式将是焦点.
naw*_*fal 11
我在互联网上尝试了几乎所有东西(所以肯定:)).充其量我可以把我的形式放在所有其他形式之上,但没有焦点(通过@Hans Passant的方法).在各地都有大量的代码,我不知怎的感觉这很容易.所以我总是使用SetForegroundWindow()其他代码块.从没想过只SetForegroundWindow()会这样做.
这很有效.
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
Process process = new Process();
process.StartInfo.FileName = @...\abc.log";
process.Start();
process.WaitForInputIdle(); //this is the key!!
SetForegroundWindow(this.Handle);
}
Run Code Online (Sandbox Code Playgroud)
有时这种方法会聚焦于父表格(如果我想要的表格是其父表格的模态子表格); 在这种情况下,只需添加this.Focus()到最后一行..
即便如此:
Microsoft.VisualBasic.Interaction.Shell(@"notepad.exe D:\abc.log",
Microsoft.VisualBasic.AppWinStyle.NormalNoFocus);
Run Code Online (Sandbox Code Playgroud)
这里提供的解决方案