gpt4 book ai didi

c# - 如何使用 C# 将窗口置于前景?

转载 作者:太空狗 更新时间:2023-10-29 20:47:49 25 4
gpt4 key购买 nike

我正在尝试带来一个窗口前景。我正在使用这段代码。但它不起作用。有人可以帮忙吗?

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);
}

代码解释

Making a window the foreground window requires more than just calling the SetForegroundWindow API. You must first determine the foreground thread and attach it to your window, using AttachThreadInput, then call SetForegroundWindow. That way they can share input states.

First I call GetForegroundWindow to get the handle of the current foreground window. Then a few calls to GetWindowThreadProcessId retrieve the threads associated with the current foreground window and the window I want to bring to the foreground. If these threads are the same a simple call to SetForegroundWindow is all that is necessary. Otherwise, the foreground thread is attached to the window that I am bringing to the front and detached from what was the current foreground window. The AttachThreadInput API handles this.

内容取自 here谢谢。

最佳答案

我以前用过这个方法:

    [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

关于c# - 如何使用 C# 将窗口置于前景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4867210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com