如何将焦点设置为嵌入Windows上的Java应用程序中的非Java应用程序

时间:2017-09-16 12:13:15

标签: java findwindow

我使用代码在Java应用程序中嵌入了一个C#应用程序。但我无法将注意力集中在C#应用程序上。

hwnd = OS.FindWindow(null, new TCHAR(0, title, true));

int oldStyle = OS.GetWindowLong(hwnd, OS.GWL_STYLE);
OS.SetWindowLong(hwnd, OS.GWL_STYLE, oldStyle & ~OS.WS_BORDER);

OS.SetParent(hwnd, composite.handle);
OS.SendMessage(hwnd, OS.WM_SYSCOMMAND, OS.SC_MAXIMIZE, 0);

OS.SetForegroundWindow(PlatformUI.getWorkbench().getWorkbenchWindows()[0].getShell().handle);

1 个答案:

答案 0 :(得分:0)

要将焦点设置为 Windows 应用程序,我使用以下方法:

必需的进口商品

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;

方法:

/**
 * Sets focus to a running windows application Windows Application. If the 
 * handle of the desired application is not found then nothing happens.<pre>
 * 
 * <b>Example Usage 1:</b>
 * 
 *      setFocusToWindowsApp("Untitled - Notepad"); 
 * 
 * <b>Example Usage 2:</b>
 * 
 *      setFocusToWindowsApp("Untitled - Notepad", 1);</pre>
 * 
 * @param applicationTitle (String) The title contained upon the application's 
 * Window Title Bar.<br>
 * 
 * @param windowState (Optional - Integer - Default is 0) By default when the
 * desired application window is set to show to the forefront on screen it is 
 * displayed in its Normal window state (not maximized or minimized). If a value
 * of 1 is supplied then the windows is brought to the forefront in its Maximized
 * state. If 2 is supplied then the window is set to is Minimized state.<pre>
 * 
 *      0   Normal (default)
 *      1   Maximized
 *      2   Minimized</pre><br>
 * 
 * A value supplied that is less that 0 or greater than 2 is automatically changed 
 * to 0 (Normal State).
 */
public void setFocusToWindowsApp(String applicationTitle, int... windowState) {
    int state = User32.SW_SHOWNORMAL; //default window state (Normal)
    if (windowState.length > 0) {
        state = windowState[0];
        switch(state) {
            default:
            case 0:
                state = User32.SW_SHOWNORMAL;
                break;
            case 1:
                state = User32.SW_SHOWMAXIMIZED;
                break;
            case 2:
                state = User32.SW_SHOWMINIMIZED;
                break;
        }
    }

    User32 user32 = User32.INSTANCE;  
    WinDef.HWND hWnd = user32.FindWindow(null, applicationTitle);
    if (user32.IsWindowVisible(hWnd)) { 
        user32.ShowWindow(hWnd, state); //.SW_SHOW); 
        user32.SetForegroundWindow(hWnd);  
        user32.SetFocus(hWnd);
    }
}

此方法还会扩展应用程序窗口,如果它已被最小化到任务栏上并设置焦点,除非当然将整数值2提供给可选的 windowState 参数,告诉方法关注应用程序但处于最小化状态。如果应用程序没有最小化,那么它可以最小化它。