Need to activate a window

不羁岁月 提交于 2019-11-27 22:36:37

SetForgroundWindow only works if its process has input focus. This is what I use:

public static void forceSetForegroundWindow( IntPtr hWnd, IntPtr mainThreadId )
{
    IntPtr foregroundThreadID = GetWindowThreadProcessId( GetForegroundWindow(), IntPtr.Zero );
    if ( foregroundThreadID != mainThreadId )
    {
        AttachThreadInput( mainThreadId, foregroundThreadID, true );
        SetForegroundWindow( hWnd );
        AttachThreadInput( mainThreadId, foregroundThreadID, false );
    }
    else
        SetForegroundWindow( hWnd );
}

You need to find the window using something like Window title and then active it as follows:

public class Win32 : IWin32
{
    //Import the FindWindow API to find our window
    [DllImport("User32.dll", EntryPoint = "FindWindow")]
    private static extern IntPtr FindWindowNative(string className, string windowName);

    //Import the SetForeground API to activate it
    [DllImport("User32.dll", EntryPoint = "SetForegroundWindow")]
    private static extern IntPtr SetForegroundWindowNative(IntPtr hWnd);

    public IntPtr FindWindow(string className, string windowName)
    {
        return FindWindowNative(className, windowName);
    }

    public IntPtr SetForegroundWindow(IntPtr hWnd)
    {
        return SetForegroundWindowNative(hWnd);
    }
}

public class SomeClass
{
    public void Activate(string title)
    {
        //Find the window, using the Window Title
        IntPtr hWnd = win32.FindWindow(null, title);
        if (hWnd.ToInt32() > 0) //If found
        {
            win32.SetForegroundWindow(hWnd); //Activate it
        }
    }
}

You have to get the form using FromHandle:

f = Control.FromHandle(handle)

then you can can call Activate on the result:

 f.Activate()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!