3

我有这样的情况。我有一个应用程序的窗口句柄。我需要激活它。我尝试了所有这些功能,但并不总是有效。(大多数情况下,它第一次不起作用,我必须手动单击它才能激活它。第二次尝试它工作正常)我的原因这样做是因为我在需要执行的表单的 Form.Activate 事件中编写了代码。应用程序是单实例应用程序。创建新实例时,它首先检查是否存在任何其他进程,如果找到,则将旧进程的句柄传递给这些函数,以便用户可以在旧窗体上工作。应用程序是从不同的 C 应用程序调用的。[DllImport("user32.dll")] public static extern int ShowWindow(IntPtr hWnd, int nCmdShow);

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

    [DllImport("user32")]
    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
4

3 回答 3

4

SetForgroundWindow 仅在其进程具有输入焦点时才有效。这就是我使用的:

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 );
}
于 2010-09-24T18:43:39.263 回答
3

您需要使用 Window title 之类的内容找到该窗口,然后按如下方式将其激活:

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
        }
    }
}
于 2010-09-24T12:37:14.910 回答
0

您必须使用 FromHandle 获取表单:

f = Control.FromHandle(handle)

然后您可以在结果上调用激活:

 f.Activate()
于 2010-09-24T12:35:19.733 回答