Maximize process from java from taskbar

有些话、适合烂在心里 提交于 2020-02-01 05:31:29

问题


If I have a process minimized in my taskbar, is there any way to maximize it from java?

I know the name of the process, but would it be possible?


回答1:


Your best bet is probably using the Windows API. I've used Java Native Access before for tasks like this. I've found the library very handy.

With JNA, what you do is you declare an interface with the exported functions of a shared library (DLL), then load the library which gets you proxy to that library.

The WinAPI functions we're interested in are the following User32 functions:

HWND WINAPI FindWindow(LPCTSTR lpClassName, LPCTSTR lpWindowName); 

BOOL WINAPI ShowWindow(HWND hWnd, int  nCmdShow); 

Our proxy interface could look like this. This interface provides very low level access, so in practice you'd probably want to encapsulate the functionality.

import com.sun.jna.win32.StdCallLibrary;

interface User32 extends StdCallLibrary {
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms633499(v=vs.85).aspx
    int FindWindowA(String className, String windowName);
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
    boolean ShowWindow(int window, int command);
}

Notice that the function name must match the API function's name exactly. If you want to use Java-style method names (camelCase instead of PascalCase), you need a custom function mapper that does the change (usage example, class definition)

To find and show your window (note, I haven't tested this, the Windows API documentation will help you out if it doesn't work):

import com.sun.jna.Native;

public class Program {
    private static final int SW_RESTORE = 9;

    public static void main(String[] args) {
        User32 user32 = Native.loadLibrary("User32.dll", User32.class);
        int window = user32.FindWindowA(null, "Google Chrome");
        boolean success = user32.ShowWindow(window, SW_RESTORE);
        if (success) {
            System.out.println("Success");
        } else {
            System.out.println("Fail: " + Native.getLastError());
        }
    }
}

Note that the window name must also match exactly, otherwise window will be 0 (NULL) and the following call will fail. I am also not sure whether SW_RESTORE works alone or if it needs another flag to go with it.

If you want to enumerate through all of the processes to find the one you're interested in, you can check out some examples from my lacuna project, the windows/WindowsPidEnumerator.java and windows/WindowsNativeProcessCollector.java files might be useful. A word of warning though, this was a course project and it has disgustingly many layers of abstraction.



来源:https://stackoverflow.com/questions/43059987/maximize-process-from-java-from-taskbar

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