[英]How to bring a window foreground using c#?
我試圖帶一個窗口前景。 我正在使用此代碼。 但它不起作用。 有人可以幫忙嗎?
ShowWindowAsync(wnd.hWnd, SW_SHOW);
SetForegroundWindow(wnd.hWnd);
// Code from Karl E. Peterson, www.mvps.org/vb/sample.htm
// Converted to Delphi by Ray Lischner
// Published in The Delphi Magazine 55, page 16
// Converted to C# by Kevin Gale
IntPtr foregroundWindow = GetForegroundWindow();
IntPtr Dummy = IntPtr.Zero;
uint foregroundThreadId = GetWindowThreadProcessId(foregroundWindow, Dummy);
uint thisThreadId = GetWindowThreadProcessId(wnd.hWnd, Dummy);
if (AttachThreadInput(thisThreadId, foregroundThreadId, true))
{
BringWindowToTop(wnd.hWnd); // IE 5.5 related hack
SetForegroundWindow(wnd.hWnd);
AttachThreadInput(thisThreadId, foregroundThreadId, false);
}
if (GetForegroundWindow() != wnd.hWnd)
{
// Code by Daniel P. Stasinski
// Converted to C# by Kevin Gale
IntPtr Timeout = IntPtr.Zero;
SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, Timeout, 0);
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Dummy, SPIF_SENDCHANGE);
BringWindowToTop(wnd.hWnd); // IE 5.5 related hack
SetForegroundWindow(wnd.hWnd);
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Timeout, SPIF_SENDCHANGE);
}
代碼解釋
將窗口設置為前景窗口不僅需要調用SetForegroundWindow API。 您必須首先確定前台線程並使用AttachThreadInput將其附加到窗口,然后調用SetForegroundWindow。 這樣他們就可以共享輸入狀態。
首先,我調用GetForegroundWindow來獲取當前前景窗口的句柄。 然后對GetWindowThreadProcessId的一些調用檢索與當前前景窗口和我想要帶到前台的窗口相關聯的線程。 如果這些線程相同,則只需調用SetForegroundWindow就可以了。 否則,前台線程將附加到我帶到前面的窗口,並與當前前景窗口分離。 AttachThreadInput API處理此問題。
內容取自此處謝謝。
我以前用過這個方法:
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
Process[] processes = Process.GetProcessesByName("processname");
SetForegroundWindow(processes[0].MainWindowHandle);
更多信息: http : //pinvoke.net/default.aspx/user32.SetForegroundWindow
此代碼恢復並將焦點設置到窗口:
[DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool SendMessage(IntPtr hWnd, Int32 msg, Int32 wParam, Int32 lParam);
static Int32 WM_SYSCOMMAND = 0x0112;
static Int32 SC_RESTORE = 0xF120;
並像這樣使用它:
var proc = Process.GetProcessesByName("YourProgram").FirstOrDefault();
if (proc != null)
{
var pointer = proc.MainWindowHandle;
SetForegroundWindow(pointer);
SendMessage(pointer, WM_SYSCOMMAND, SC_RESTORE, 0);
}
你應該使用SetForegroundWindow。 對你來說, C#Force Form Focus可能也很有趣
我將簡要介紹一下: Form.BringToFront()
從Windows 7開始,這些功能的表現並不是很好。 如果在應用程序前面有一個應用程序(如Excel),那么Windows 7會阻止它並閃爍窗口。 您可以在HKEY_CURRENT_USER \\ Control Panel \\ Desktop中設置注冊表超時設置ForegroundLockTimeout = 0,但這些設置稱為竊取焦點。 要設置XP“應該”的行為以及默認情況下在Windows 7中的行為,您可以創建/設置值為0x00030D40(200000ms)。 我想知道可信Windows應用程序的首選解決方案是什么。 例如。 當我雙擊應用程序A中的某些內容時,我相信應用程序B可以獲得焦點,而其他一些應用程序則模糊了應用程序B的窗口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.