2012-05-22 60 views
-2

操作系統:Windows 7開放程序的定義

請問如何自動識別在後臺運行的java程序,哪個窗口現在處於活動狀態?

通過GOOGLETRANSLATE

+1

瞭解如何使用'用java的Win32 API'。有關更多信息,請查看此[問題](http://stackoverflow.com/q/6391439/776084)。 – RanRag

+1

爲什麼downvoting?這不是我在這裏看到的更糟糕的問題。 TorTTT請解釋你到目前爲止嘗試過什麼。 – BigMike

回答

1

RanRag翻譯,感謝link

要確定哪些程序屬於活動窗口,你必須:

1)下載jna.jar和platform.jar從JNA - Download page

2)將庫連接到項目

3)添加代碼:

private static class Psapi { 
     static { Native.register("psapi"); } 
     public static native int GetModuleBaseNameW(Pointer hProcess, Pointer hmodule, char[] lpBaseName, int size); 
    } 

    private static class Kernel32 { 
     static { Native.register("kernel32"); } 
     public static int PROCESS_QUERY_INFORMATION = 0x0400; 
     public static int PROCESS_VM_READ = 0x0010; 
     public static native int GetLastError(); 
     public static native Pointer OpenProcess(int dwDesiredAccess, boolean bInheritHandle, Pointer pointer); 
    } 

    private static class User32DLL { 
     static { Native.register("user32"); } 
     public static native int GetWindowThreadProcessId(WinDef.HWND hWnd, PointerByReference pref); 
     public static native WinDef.HWND GetForegroundWindow(); 
     public static native int GetWindowTextW(WinDef.HWND hWnd, char[] lpString, int nMaxCount); 
    } 

    private static final int MAX_TITLE_LENGTH = 1024; 

    public void nameApplication() { 

     Psapi ps = new Psapi(); 
     Kernel32 kr = new Kernel32(); 
     User32DLL us = new User32DLL(); 

     char[] buffer = new char[MAX_TITLE_LENGTH * 2]; 
     String nameApp; 

     us.GetWindowTextW(us.GetForegroundWindow(), buffer, MAX_TITLE_LENGTH); 
     System.out.println("Active window title: " + Native.toString(buffer)); 

     PointerByReference pointer = new PointerByReference(); 
     us.GetWindowThreadProcessId(us.GetForegroundWindow(), pointer); 
     Pointer process = kr.OpenProcess(kr.PROCESS_QUERY_INFORMATION | kr.PROCESS_VM_READ, false, pointer.getValue()); 
     ps.GetModuleBaseNameW(process, null, buffer, MAX_TITLE_LENGTH); 
     System.out.println("Active window process: " + Native.toString(buffer);); 

    }