如何使用C#调出窗口前景? [英] How to bring a window foreground using c#?

查看:74
本文介绍了如何使用C#调出窗口前景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to bring a window foreground. I am using this code. But its not working. Could someone please help?

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.这样他们可以共享输入状态.

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.

首先,我将GetForegroundWindow调用为得到当前的句柄前景窗口.然后打几个电话到GetWindowThreadProcessId检索与当前关联的线程前景窗口和我的窗口希望带到前台.如果这些线程一样简单到SetForegroundWindow的所有调用那是必要的.否则,前台线程已连接到我带到前面的窗户脱离了当下前景窗口.这AttachThreadInput API可以处理此问题.

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.

内容取自此处谢谢.

推荐答案

我以前使用过此方法:

    [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#调出窗口前景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆