JNA OpenProcess返回" null"经过一段时间的循环

时间:2018-01-14 23:38:12

标签: java jna loadlibrary user32 kernel32

我有一个正在寻找系统范围内的功能的流程'窗口位于屏幕顶部。在第一分钟,它工作正常,但过了一段时间后," OpenProcess-call"每次运行都返回null。我认为这是一个内存问题,因为我还有其他一些内存问题,但设法修复它们。 那是我的代码:

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.StdCallLibrary;


public class Test3Class
{
    public static void main(String[] args)
    {
        IntByReference pid = new IntByReference();
        byte[] exePathname = new byte[512];
        Pointer zero = new Pointer(0);
        while (true)
        {
            String task = getForegroundTask(pid, exePathname, zero);
        }
    }

    public interface MyUser32 extends StdCallLibrary
    {
        MyUser32 INSTANCE = (MyUser32) Native.loadLibrary("user32", User32.class);
        int GetWindowThreadProcessId(HWND hwnd, IntByReference pid);
    };

    public interface Kernel32 extends StdCallLibrary
    {
        Kernel32 INSTANCE = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class);
        public Pointer OpenProcess(int dwDesiredAccess, boolean bInheritHandle, int dwProcessId);
        public int GetTickCount();
    };

    public interface psapi extends StdCallLibrary
    {
        psapi INSTANCE = (psapi)Native.loadLibrary("psapi", psapi.class);
        int GetModuleFileNameExA (Pointer process, Pointer hModule, byte[] lpString, int nMaxCount);
    };


    public static String getForegroundTask(IntByReference pid, byte[] exePathname, Pointer zero)
    {
        HWND hwnd = User32.INSTANCE.GetForegroundWindow();
        User32.INSTANCE.GetWindowThreadProcessId(hwnd, pid);
        Pointer process = Kernel32.INSTANCE.OpenProcess(0x0400, false, pid.getValue()); // <-- !!! Becomes null !!!
        int result = psapi.INSTANCE.GetModuleFileNameExA(process, zero, exePathname, 512);
        String[] list = Native.toString(exePathname).substring(0, result).split("\\\\");
        String task = list[list.length-1];
        return task;
    }
}

所以首先一切都按预期工作,但是在#34; getForegroundTask&#34; hwnd stay&#34; native @ 0x301aa&#34; (如果eclipse在前台)但是进程变为&#34; null&#34 ;,结果变为&#34; 0&#34;并且任务变为空字符串。

我希望你们能在这里帮助我,因为你可以想到,我从未对JNA及其LoadLibrary函数做过任何事情。

0 个答案:

没有答案
相关问题