如何使用c#引入窗口前景?

Nik*_*kil 6 c# winapi window foreground

我试图带一个窗口前景.我正在使用此代码.但它不起作用.有人可以帮忙吗?

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);
 }
Run Code Online (Sandbox Code Playgroud)

代码解释

将窗口设置为前景窗口不仅需要调用SetForegroundWindow API.您必须首先确定前台线程并使用AttachThreadInput将其附加到窗口,然后调用SetForegroundWindow.这样他们就可以共享输入状态.

首先,我调用GetForegroundWindow来获取当前前景窗口的句柄.然后对GetWindowThreadProcessId的一些调用检索与当前前景窗口和我想要带到前台的窗口相关联的线程.如果这些线程相同,则只需调用SetForegroundWindow就可以了.否则,前台线程将附加到我带到前面的窗口,并与当前前景窗口分离.AttachThreadInput API处理此问题.

内容取自此处 谢谢.

use*_*ser 12

我以前用过这个方法:

    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    Process[] processes = Process.GetProcessesByName("processname");
    SetForegroundWindow(processes[0].MainWindowHandle);
Run Code Online (Sandbox Code Playgroud)

更多信息:http: //pinvoke.net/default.aspx/user32.SetForegroundWindow


Nic*_*rin 6

此代码恢复并将焦点设置到窗口:

    [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;
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

    var proc = Process.GetProcessesByName("YourProgram").FirstOrDefault();

    if (proc != null)
    {
        var pointer = proc.MainWindowHandle;

        SetForegroundWindow(pointer);
        SendMessage(pointer, WM_SYSCOMMAND, SC_RESTORE, 0);
    }
Run Code Online (Sandbox Code Playgroud)


Ant*_*nov 1

您应该使用 SetForegroundWindow。您也可能会感兴趣C# Force Form Focus