Red*_*ter 31 c# visual-studio-2008 winforms
我正在用C#编写Windows窗体应用程序.我需要能够把它带到前台.经过一些谷歌搜索和实验,我有一个看起来非常hacky的工作解决方案.
如果有的话,我想知道这样做的优雅方式.我需要应用程序恢复并前往前台,无论它是最小化,还是最小化,但在后台.
当前代码如下所示:
WindowState = FormWindowState.Minimized;
WindowState = FormWindowState.Normal;
BringToFront();
Focus();
Run Code Online (Sandbox Code Playgroud)
bob*_*mcr 51
你试过Form.Activate吗?
此代码似乎可以执行您想要的操作,如果最小化则将表单恢复为正常大小,然后激活它以设置焦点:
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
}
this.Activate();
Run Code Online (Sandbox Code Playgroud)
警告:这很烦人!如果它只是一个供您个人使用的应用程序,正如您所说,也许您可以忍受它.:)
Joh*_*ohn 11
注意.下面我复制了一个链接问题中投票最多的答案,该问题与此问题相同.答案是我发现解决这个问题的唯一纯粹的C#答案.
this.WindowState = FormWindowState.Minimized;
this.Show();
this.WindowState = FormWindowState.Normal;
Run Code Online (Sandbox Code Playgroud)
它总是将所需的窗口带到所有其他窗口的前面.
private static class User32
{
[DllImport("User32.dll")]
internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
internal static readonly IntPtr InvalidHandleValue = IntPtr.Zero;
internal const int SW_MAXIMIZE = 3;
}
public void Activate()
{
Process currentProcess = Process.GetCurrentProcess();
IntPtr hWnd = currentProcess.MainWindowHandle;
if (hWnd != User32.InvalidHandleValue)
{
User32.SetForegroundWindow(hWnd);
User32.ShowWindow(hWnd, User32.SW_MAXIMIZE);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以设置.TopMost
为true,调用DoEvents()
,然后设置.TopMost
回false.它仍然是hackish,但如果Activate和Show不起作用,它比最小化/重新显示更好.
归档时间: |
|
查看次数: |
36890 次 |
最近记录: |