Search code examples
javawinapijna

How can I get HWND from String?


I have many windows with same names, For example Calculator.

User32Extra.INSTANCE.FindWindow(null,"Calculator")

The above Script gives me HWND of first Calculator found.

I have used EnumWindows to find all the HWNDs.

final HashMap<HWND,String> hm=new HashMap<HWND,String>();  
User32.INSTANCE.EnumWindows(new User32.WNDENUMPROC() {

     @Override
     public boolean callback(Pointer hWnd, Pointer arg) {
         HWND hWnd2 = new HWND(hWnd);
        byte[] windowText = new byte[512];
        User32.INSTANCE.GetWindowTextA(hWnd, windowText, 512);
        String wText = Native.toString(windowText).trim();

        if (!wText.isEmpty() && User32.INSTANCE.IsWindowVisible(hWnd2) && wText.equals("Calculator")) {
            hm.put(hWnd2,wText);
        }
        return true;
     }
  }, null);

for(HWND hwnd:hm.keySet()){
   System.out.println(hwnd.toString());
}

The above script gives output as

native@0x20816

native@0x50362

native@0x1206ae

I don't have access of this HashMap in another program. I know only the String value of HWND. Is it possible to cast native@0x20816 String to HWND?

If so How can I do that? Please help..


Solution

  • String hwndString = "native@0xa021c";
    HWND temp = new HWND();
    temp.setPointer(new Pointer(Long.decode(hwndString.substring(7))));
    if(User32.INSTANCE.IsWindow(temp)){
         //This is a valid window
    }
    else{
         // Invalid Window
    }