简体   繁体   中英

How do I get the "native" window handle in Java to be passed via JNI to C++ written DLL?

I have to force an existing JavaFX application to be "always in background", but I wasn't able to find that functionality natively in JavaFX (only always on top exists), hence I thought to use the Win32 API from an external JNI DLL to call the SetWindowPos() function.

I was able to link Java to C++, but I don't know how to get the native window handle ( HWND ) required by the function from the Java environment.

My sample call (from within the DLL):

#define X0 0
#define Y0 0
#define W 1920
#define H 1080
#define FLAGS 0
#define ALWAYS_ON_BOTTOM HWND_BOTTOM
#define I_DONT_KNOW_WHAT nullptr

JNIEXPORT void JNICALL Java_libreria_WindowsHandlerWrapper_SetAlwaysOnBottom
(JNIEnv* env, jobject obj) {
   
    HWND hWnd = I_DONT_KNOW_WHAT; /* here is where I need help*/

    SetWindowPos(
        hWnd,
        ALWAYS_ON_BOTTOM,
        X0,
        Y0,
        W,
        H,
        FLAGS
    );
}

What I don't know is how to get the hWnd handle.

This is what I did:
0> I set the stage's title (MyApp's name)
1> I passed (hard-coded) the title as a wstring to the dll
2> I searched by title what was my process using windows' getHwnd API
3> I finally got the needed HWND

//I had to call this in the C++ to get the HWND from the title
HWND getHwnd(std::wstring title) {
    HWND hwnd = NULL;
    hwnd = FindWindow(NULL,title.c_str());
    return hwnd;
}

The call became:

#define X0 0
#define Y0 0
#define W 1920
#define H 1080
#define FLAGS 0
#define ALWAYS_ON_BOTTOM HWND_BOTTOM
#define I_DONT_KNOW_WHAT nullptr

JNIEXPORT void JNICALL Java_libreria_WindowsHandlerWrapper_SetAlwaysOnBottom
(JNIEnv* env, jobject obj) {
HWND hWnd = getHwnd(L"My App's name");
    

        SetWindowPos(
            hWnd,
            wpos,
            x0,
            y0,
            w,
            h,
            FLAGS
        );
}
        

I don't like the fact I have to rely to something the user can see (the title) but, for now, it solved my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM