3

私はこのような状況にあります。アプリケーションのウィンドウハンドルがあります。アクティベートする必要があります。これらすべての機能を試しましたが、常に機能するとは限りません(ほとんどの場合、最初は機能しないため、手動でクリックしてアクティブにする必要があります。2回目以降は正常に機能します)これを行っているのは、実行する必要のあるフォームの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)

次に、結果に対して Activate を呼び出すことができます。

 f.Activate()
于 2010-09-24T12:35:19.733 に答える