Java Examples for com.sun.jna.platform.win32.WinNT.HANDLE

The following java examples will help you to understand the usage of com.sun.jna.platform.win32.WinNT.HANDLE. These source code samples are taken from different open source projects.

Example 1
Project: Red-master  File: WindowsProcessTreeHandler.java View source code
@Override
public long getProcessPid(final Process process) {
    long pid = ProcessInformation.PROCESS_NOT_FOUND;
    try {
        final Field f = process.getClass().getDeclaredField("handle");
        f.setAccessible(true);
        long handle = f.getLong(process);
        Kernel32 kernel = Kernel32.INSTANCE;
        HANDLE winHandle = new HANDLE();
        winHandle.setPointer(Pointer.createConstant(handle));
        pid = kernel.GetProcessId(winHandle);
    } catch (Throwable e) {
    }
    return pid;
}
Example 2
Project: SnippingToolPlusPlus-master  File: ActiveWindowModule.java View source code
public static BufferedImage capture() {
    HWND hwnd = User32.INSTANCE.GetForegroundWindow();
    HDC hdcWindow = User32.INSTANCE.GetDC(hwnd);
    HDC hdcMemDC = GDI32.INSTANCE.CreateCompatibleDC(hdcWindow);
    RECT bounds = new RECT();
    User32Extra.INSTANCE.GetClientRect(hwnd, bounds);
    int width = bounds.right - bounds.left;
    int height = bounds.bottom - bounds.top;
    HBITMAP hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcWindow, width, height);
    HANDLE hOld = GDI32.INSTANCE.SelectObject(hdcMemDC, hBitmap);
    GDI32Extra.INSTANCE.BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, WinGDIExtra.SRCCOPY);
    GDI32.INSTANCE.SelectObject(hdcMemDC, hOld);
    GDI32.INSTANCE.DeleteDC(hdcMemDC);
    BITMAPINFO bmi = new BITMAPINFO();
    bmi.bmiHeader.biWidth = width;
    bmi.bmiHeader.biHeight = -height;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;
    bmi.bmiHeader.biCompression = WinGDI.BI_RGB;
    Memory buffer = new Memory(width * height * 4);
    GDI32.INSTANCE.GetDIBits(hdcWindow, hBitmap, 0, height, buffer, bmi, WinGDI.DIB_RGB_COLORS);
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    image.setRGB(0, 0, width, height, buffer.getIntArray(0, width * height), 0, width);
    GDI32.INSTANCE.DeleteObject(hBitmap);
    User32.INSTANCE.ReleaseDC(hwnd, hdcWindow);
    return image;
}
Example 3
Project: jna-master  File: Advapi32Test.java View source code
public void testOpenThreadTokenNoToken() {
    HANDLEByReference phToken = new HANDLEByReference();
    HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread();
    assertNotNull(threadHandle);
    assertFalse(Advapi32.INSTANCE.OpenThreadToken(threadHandle, WinNT.TOKEN_READ, false, phToken));
    assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError());
}
Example 4
Project: ClewareUSB-master  File: HiDeviceWin.java View source code
private void open() {
    final Guid.GUID.ByReference hidDevices = getHidDevicesGuid();
    final HANDLE deviceInfoList = SetupApi.INSTANCE.SetupDiGetClassDevs(hidDevices, null, null, SetupApi.DIGCF_DEVICEINTERFACE | SetupApi.DIGCF_PRESENT);
    if (WinBase.INVALID_HANDLE_VALUE == deviceInfoList) {
        throw new LastErrorException(Native.getLastError());
    }
    try {
        for (int index = 0; ; index++) {
            // Loop exits with HIDDeviceNotFoundException
            final String devicePath = getDevicePath(hidDevices, deviceInfoList, index);
            final WinNT.HANDLE deviceHandle = getDeviceHandle(devicePath);
            final USBAddress usbAddress = getUsbAddress(deviceHandle);
            if (usbAddress.equals(address)) {
                handle = deviceHandle;
                break;
            } else {
                Kernel32.INSTANCE.CloseHandle(deviceHandle);
            }
        }
    } finally {
        SetupApi.INSTANCE.SetupDiDestroyDeviceInfoList(deviceInfoList);
    }
}
Example 5
Project: buck-master  File: WindowsNamedPipe.java View source code
/** Creates a Windows named pipe bound to a path */
public static WindowsNamedPipe createPipeWithPath(String path) throws IOException {
    HANDLE pipeHandle = api.CreateFile(path, WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_FLAG_OVERLAPPED, null);
    if (WinNT.INVALID_HANDLE_VALUE.equals(pipeHandle)) {
        throw new IOException("Failed to open a named pipe " + path + " error: " + api.GetLastError());
    }
    return new WindowsNamedPipe(pipeHandle, createEvent(), createEvent());
}
Example 6
Project: jna-mirror-master  File: WindowUtils.java View source code
protected void paintDirect(BufferedImage buf, Rectangle bounds) {
    // TODO: paint frame decoration if window is decorated
    Window win = SwingUtilities.getWindowAncestor(this);
    GDI32 gdi = GDI32.INSTANCE;
    User32 user = User32.INSTANCE;
    int x = bounds.x;
    int y = bounds.y;
    Point origin = SwingUtilities.convertPoint(this, x, y, win);
    int w = bounds.width;
    int h = bounds.height;
    int ww = win.getWidth();
    int wh = win.getHeight();
    HDC screenDC = user.GetDC(null);
    HANDLE oldBitmap = null;
    try {
        if (memDC == null) {
            memDC = gdi.CreateCompatibleDC(screenDC);
        }
        if (hBitmap == null || !win.getSize().equals(bitmapSize)) {
            if (hBitmap != null) {
                gdi.DeleteObject(hBitmap);
                hBitmap = null;
            }
            BITMAPINFO bmi = new BITMAPINFO();
            bmi.bmiHeader.biWidth = ww;
            bmi.bmiHeader.biHeight = wh;
            bmi.bmiHeader.biPlanes = 1;
            bmi.bmiHeader.biBitCount = 32;
            bmi.bmiHeader.biCompression = WinGDI.BI_RGB;
            bmi.bmiHeader.biSizeImage = ww * wh * 4;
            PointerByReference ppbits = new PointerByReference();
            hBitmap = gdi.CreateDIBSection(memDC, bmi, WinGDI.DIB_RGB_COLORS, ppbits, null, 0);
            pbits = ppbits.getValue();
            bitmapSize = new Dimension(ww, wh);
        }
        oldBitmap = gdi.SelectObject(memDC, hBitmap);
        Raster raster = buf.getData();
        int[] pixel = new int[4];
        int[] bits = new int[w];
        for (int row = 0; row < h; row++) {
            for (int col = 0; col < w; col++) {
                raster.getPixel(col, row, pixel);
                int alpha = (pixel[3] & 0xFF) << 24;
                int red = (pixel[2] & 0xFF);
                int green = (pixel[1] & 0xFF) << 8;
                int blue = (pixel[0] & 0xFF) << 16;
                bits[col] = alpha | red | green | blue;
            }
            int v = wh - (origin.y + row) - 1;
            pbits.write((v * ww + origin.x) * 4, bits, 0, bits.length);
        }
        SIZE winSize = new SIZE();
        winSize.cx = win.getWidth();
        winSize.cy = win.getHeight();
        POINT winLoc = new POINT();
        winLoc.x = win.getX();
        winLoc.y = win.getY();
        POINT srcLoc = new POINT();
        BLENDFUNCTION blend = new BLENDFUNCTION();
        HWND hWnd = getHWnd(win);
        // extract current constant alpha setting, if possible
        ByteByReference bref = new ByteByReference();
        IntByReference iref = new IntByReference();
        byte level = getAlpha(win);
        try {
            // GetLayeredwindowAttributes supported WinXP and later
            if (user.GetLayeredWindowAttributes(hWnd, null, bref, iref) && (iref.getValue() & WinUser.LWA_ALPHA) != 0) {
                level = bref.getValue();
            }
        } catch (UnsatisfiedLinkError e) {
        }
        blend.SourceConstantAlpha = level;
        blend.AlphaFormat = WinUser.AC_SRC_ALPHA;
        user.UpdateLayeredWindow(hWnd, screenDC, winLoc, winSize, memDC, srcLoc, 0, blend, WinUser.ULW_ALPHA);
    } finally {
        user.ReleaseDC(null, screenDC);
        if (memDC != null && oldBitmap != null) {
            gdi.SelectObject(memDC, oldBitmap);
        }
    }
}
Example 7
Project: platform_build-master  File: WindowsNamedPipe.java View source code
/** Creates a Windows named pipe bound to a path */
public static WindowsNamedPipe createPipeWithPath(String path) throws IOException {
    HANDLE pipeHandle = api.CreateFile(path, WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_FLAG_OVERLAPPED, null);
    if (WinNT.INVALID_HANDLE_VALUE.equals(pipeHandle)) {
        throw new IOException("Failed to open a named pipe " + path + " error: " + api.GetLastError());
    }
    return new WindowsNamedPipe(pipeHandle, createEvent(), createEvent());
}
Example 8
Project: HearthStats.net-Uploader-master  File: ProgramHelperWindows.java View source code
private BufferedImage _getScreenCaptureWindows(HWND hWnd) {
    HDC hdcWindow = User32.INSTANCE.GetDC(hWnd);
    HDC hdcMemDC = GDI32.INSTANCE.CreateCompatibleDC(hdcWindow);
    RECT bounds = new RECT();
    User32Extra.INSTANCE.GetClientRect(hWnd, bounds);
    if (bounds.toRectangle().width >= 1024) {
        if (isMinimised) {
            _notifyObserversOfChangeTo("Hearthstone window restored");
            isMinimised = false;
        }
        if (isFullScreen(bounds.toRectangle())) {
            if (!isFullscreenFlag) {
                _notifyObserversOfChangeTo("Hearthstone running in fullscreen");
                isFullscreenFlag = true;
            }
            return null;
        } else {
            int width = bounds.right - bounds.left;
            int height = bounds.bottom - bounds.top;
            HBITMAP hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcWindow, width, height);
            HANDLE hOld = GDI32.INSTANCE.SelectObject(hdcMemDC, hBitmap);
            GDI32Extra.INSTANCE.BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, WinGDIExtra.SRCCOPY);
            GDI32.INSTANCE.SelectObject(hdcMemDC, hOld);
            GDI32.INSTANCE.DeleteDC(hdcMemDC);
            BITMAPINFO bmi = new BITMAPINFO();
            bmi.bmiHeader.biWidth = width;
            bmi.bmiHeader.biHeight = -height;
            bmi.bmiHeader.biPlanes = 1;
            bmi.bmiHeader.biBitCount = 32;
            bmi.bmiHeader.biCompression = WinGDI.BI_RGB;
            Memory buffer = new Memory(width * height * 4);
            GDI32.INSTANCE.GetDIBits(hdcWindow, hBitmap, 0, height, buffer, bmi, WinGDI.DIB_RGB_COLORS);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            image.setRGB(0, 0, width, height, buffer.getIntArray(0, width * height), 0, width);
            GDI32.INSTANCE.DeleteObject(hBitmap);
            User32.INSTANCE.ReleaseDC(hWnd, hdcWindow);
            return image;
        }
    }
    if (!isMinimised) {
        // that the window has been minimised.
        if (minimisedCount < ITERATIONS_FOR_MINIMISE) {
            minimisedCount++;
        } else {
            _notifyObserversOfChangeTo("Warning! Hearthstone minimized. No detection possible.");
            isMinimised = true;
            minimisedCount = 0;
        }
    }
    return null;
}
Example 9
Project: massif-master  File: MatlabRunningManager.java View source code
private static boolean isWow64Machine(Kernel32 kernel32) {
    HANDLE curProcessHandle = kernel32.GetCurrentProcess();
    // create value to be passed as reference, and initialize with a value
    // different from a "BOOL" one (0 or 1)
    IntByReference isWow64 = new IntByReference(42);
    kernel32.IsWow64Process(curProcessHandle, isWow64);
    // check if it is running on a 32-bits or 64-bits machine
    boolean isWow64Process = (isWow64.getValue() == 1);
    boolean isWow64Pointer = (Pointer.SIZE == 8);
    boolean isWow64Machine = isWow64Process || isWow64Pointer;
    return isWow64Machine;
}
Example 10
Project: oshi-master  File: WindowsOperatingSystem.java View source code
private List<OSProcess> processMapToList(Map<String, List<Object>> procs) {
    long now = System.currentTimeMillis();
    List<OSProcess> procList = new ArrayList<>();
    List<String> groupList = new ArrayList<>();
    List<String> groupIDList = new ArrayList<>();
    // All map lists should be the same length. Pick one size and iterate
    final int procCount = procs.get("Name").size();
    int myPid = getProcessId();
    for (int p = 0; p < procCount; p++) {
        OSProcess proc = new OSProcess();
        proc.setName((String) procs.get("Name").get(p));
        proc.setPath((String) procs.get("ExecutablePath").get(p));
        proc.setCommandLine((String) procs.get("CommandLine").get(p));
        proc.setProcessID(((Long) procs.get("ProcessID").get(p)).intValue());
        if (myPid == proc.getProcessID()) {
            proc.setCurrentWorkingDirectory(new File(".").getAbsolutePath());
        }
        proc.setParentProcessID(((Long) procs.get("ParentProcessId").get(p)).intValue());
        proc.setUser((String) procs.get("PROCESS_GETOWNER").get(p));
        proc.setUserID((String) procs.get("PROCESS_GETOWNERSID").get(p));
        // Only do for single-process queries
        if (procCount == 1) {
            final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION | WinNT.PROCESS_VM_READ, false, proc.getProcessID());
            if (pHandle != null) {
                final HANDLEByReference phToken = new HANDLEByReference();
                if (Advapi32.INSTANCE.OpenProcessToken(pHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)) {
                    Account[] accounts = Advapi32Util.getTokenGroups(phToken.getValue());
                    // get groups
                    groupList.clear();
                    groupIDList.clear();
                    for (Account account : accounts) {
                        groupList.add(account.name);
                        groupIDList.add(account.sidString);
                    }
                    proc.setGroup(FormatUtil.join(",", groupList));
                    proc.setGroupID(FormatUtil.join(",", groupIDList));
                } else {
                    int error = Kernel32.INSTANCE.GetLastError();
                    // fail
                    if (error != ERROR_ACCESS_DENIED) {
                        LOG.error("Failed to get process token for process {}: {}", proc.getProcessID(), Kernel32.INSTANCE.GetLastError());
                    }
                }
            }
            Kernel32.INSTANCE.CloseHandle(pHandle);
        }
        switch(((Long) procs.get("ExecutionState").get(p)).intValue()) {
            case READY:
            case SUSPENDED_READY:
                proc.setState(OSProcess.State.SLEEPING);
                break;
            case BLOCKED:
            case SUSPENDED_BLOCKED:
                proc.setState(OSProcess.State.WAITING);
                break;
            case RUNNING:
                proc.setState(OSProcess.State.RUNNING);
                break;
            case GROWING:
                proc.setState(OSProcess.State.NEW);
                break;
            case TERMINATED:
                proc.setState(OSProcess.State.ZOMBIE);
                break;
            case STOPPED:
                proc.setState(OSProcess.State.STOPPED);
                break;
            case UNKNOWN:
            case OTHER:
            default:
                proc.setState(OSProcess.State.OTHER);
                break;
        }
        proc.setThreadCount(((Long) procs.get("ThreadCount").get(p)).intValue());
        proc.setPriority(((Long) procs.get("Priority").get(p)).intValue());
        proc.setVirtualSize(ParseUtil.parseLongOrDefault((String) procs.get("VirtualSize").get(p), 0L));
        proc.setResidentSetSize(ParseUtil.parseLongOrDefault((String) procs.get("WorkingSetSize").get(p), 0L));
        // Kernel and User time units are 100ns
        proc.setKernelTime(ParseUtil.parseLongOrDefault((String) procs.get("KernelModeTime").get(p), 0L) / 10000L);
        proc.setUserTime(ParseUtil.parseLongOrDefault((String) procs.get("UserModeTime").get(p), 0L) / 10000L);
        proc.setStartTime((Long) procs.get("CreationDate").get(p));
        proc.setUpTime(now - proc.getStartTime());
        proc.setBytesRead((Long) procs.get("ReadTransferCount").get(p));
        proc.setBytesWritten((Long) procs.get("WriteTransferCount").get(p));
        procList.add(proc);
    }
    return procList;
}
Example 11
Project: synthuse-src-master  File: Api.java View source code
// creates highlight around selected window
public static void highlightWindow(HWND hwnd, int x, int y, int x2, int y2) {
    //COLORREF i.e. 0x00804070  Red = 0x70 green = 0x40 blue = 0x80
    //g_hRectanglePen = CreatePen (PS_SOLID, 3, RGB(256, 0, 0));
    //RGB(255, 0, 0)
    HPEN rectPen = Gdi32Ex.instance.CreatePen(PS_SOLID, 3, 0x00000099);
    HDC dc = User32Ex.instance.GetWindowDC(hwnd);
    if (dc != null) {
        // Select our created pen into the DC and backup the previous pen.
        HANDLE prevPen = Gdi32Ex.instance.SelectObject(dc, rectPen);
        // Select a transparent brush into the DC and backup the previous brush.
        HANDLE prevBrush = Gdi32Ex.instance.SelectObject(dc, Gdi32Ex.instance.GetStockObject(HOLLOW_BRUSH));
        // Draw a rectangle in the DC covering the entire window area of the found window.
        Gdi32Ex.instance.Rectangle(dc, x, y, x2, y2);
        // Reinsert the previous pen and brush into the found window's DC.
        Gdi32Ex.instance.SelectObject(dc, prevPen);
        Gdi32Ex.instance.SelectObject(dc, prevBrush);
        // Finally release the DC.
        User32Ex.instance.ReleaseDC(hwnd, dc);
    }
}
Example 12
Project: log4jna-master  File: Win32EventLogAppender.java View source code
/**
	 * @param server The server for remote logging
	 * @param source The Event View Source
	 * @param application The Event View application (location)
	 * @param eventMessageFile The message file location in the file system
	 * @param categoryMessageFile The message file location in the file system
	 * @return
	 */
private HANDLE registerEventSource(String server, String source, String application, String eventMessageFile, String categoryMessageFile) {
    String applicationKeyPath = EVENT_LOG_PATH + application;
    String eventSourceKeyPath = applicationKeyPath + "\\" + source;
    if (Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, applicationKeyPath)) {
        if (Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, eventSourceKeyPath)) {
            setVariableKeys(eventMessageFile, categoryMessageFile, eventSourceKeyPath);
        } else {
            createAndSetAllKeys(eventMessageFile, categoryMessageFile, eventSourceKeyPath);
        }
    } else {
        createAndSetAllKeys(eventMessageFile, categoryMessageFile, eventSourceKeyPath);
    }
    HANDLE h = Advapi32.INSTANCE.RegisterEventSource(server, source);
    if (h == null) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    return h;
}
Example 13
Project: mariadb-connector-j-master  File: SharedMemorySocket.java View source code
/*
    Create a mutex to synchronize login. Without mutex, different connections that are created at about the same
    time, could get the same connection number. Note, that this mutex, or any synchronization does not exist in
    in either C or .NET connectors (i.e they are racy)
    */
private HANDLE lockMutex() throws IOException {
    PointerByReference securityDescriptor = new PointerByReference();
    Advapi32.INSTANCE.ConvertStringSecurityDescriptorToSecurityDescriptor(EVERYONE_SYNCHRONIZE_SDDL, 1, securityDescriptor, null);
    Advapi32.SECURITY_ATTRIBUTES sa = new Advapi32.SECURITY_ATTRIBUTES();
    sa.nLength = sa.size();
    sa.lpSecurityDescriptor = securityDescriptor.getValue();
    sa.bInheritHandle = false;
    HANDLE mutex = Kernel32.INSTANCE.CreateMutex(sa, false, memoryName + "_CONNECT_MUTEX");
    Kernel32.INSTANCE.LocalFree(securityDescriptor.getValue());
    if (Kernel32.INSTANCE.WaitForSingleObject(mutex, timeout) == -1) {
        Kernel32.INSTANCE.CloseHandle(mutex);
        throw new IOException("wait failed (timeout, last error =  " + Kernel32.INSTANCE.GetLastError());
    }
    return mutex;
}
Example 14
Project: symmetric-ds-master  File: WindowsService.java View source code
@Override
protected boolean isPidRunning(int pid) {
    boolean isRunning = false;
    if (pid != 0) {
        Kernel32 kernel = Kernel32.INSTANCE;
        HANDLE process = kernel.OpenProcess(Kernel32.SYNCHRONIZE, false, pid);
        if (process != null) {
            int rc = kernel.WaitForSingleObject(process, 0);
            kernel.CloseHandle(process);
            isRunning = (rc == Kernel32.WAIT_TIMEOUT);
        }
    }
    return isRunning;
}
Example 15
Project: jpexs-decompiler-master  File: Win32ProcessTools.java View source code
public static List<MEMORY_BASIC_INFORMATION> getPageRanges(WinNT.HANDLE hOtherProcess) {
    List<MEMORY_BASIC_INFORMATION> ret = new ArrayList<>();
    MEMORY_BASIC_INFORMATION mbi;
    WinBase.SYSTEM_INFO si = new WinBase.SYSTEM_INFO();
    Kernel32.INSTANCE.GetSystemInfo(si);
    Pointer lpMem = si.lpMinimumApplicationAddress;
    while (pointerToAddress(lpMem) < pointerToAddress(si.lpMaximumApplicationAddress)) {
        mbi = new MEMORY_BASIC_INFORMATION();
        BaseTSD.SIZE_T t = Kernel32.INSTANCE.VirtualQueryEx(hOtherProcess, lpMem, mbi, new BaseTSD.SIZE_T(mbi.size()));
        if (t.longValue() == 0) {
            Logger.getLogger(Win32ProcessTools.class.getName()).log(Level.SEVERE, "Cannot get page ranges. Last error:" + Kernel32.INSTANCE.GetLastError());
            break;
        }
        ret.add(mbi);
        lpMem = new Pointer(pointerToAddress(mbi.baseAddress) + mbi.regionSize.longValue());
    }
    return ret;
}
Example 16
Project: windows-wrapper-master  File: WindowsXPProcess.java View source code
/**
	 * Gets the process.
	 *
	 * @param pid
	 *            the pid
	 *
	 * @return the process
	 */
public static Process getProcess(int pid) {
    WindowsXPProcess result = new WindowsXPProcess();
    HANDLE hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_ALL_ACCESS, false, pid);
    if (hProcess == null)
        hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_QUERY_INFORMATION, false, pid);
    if (hProcess == null)
        return null;
    result._pid = pid;
    result._processInformation = new MyKernel32.PROCESS_INFORMATION();
    result._processInformation.dwProcessId = pid;
    result._processInformation.hProcess = hProcess;
    result._cmd = result.getCommandLineInternal();
    // on win64 PEB of 64 bit cannot be accessed from wow -> use wmi
    if (result._cmd.equals("?"))
        result._cmd = result.getCommandLineInternalWMI();
    if ("?".equals(result._cmd)) {
        System.err.println("Could not get commandline");
    } else
        System.out.println("Command line of " + pid + ": " + result._cmd);
    PointerByReference hToken = new PointerByReference();
    HANDLE hp = new HANDLE();
    hp.setPointer(hProcess.getPointer());
    if (MyAdvapi.INSTANCE.OpenProcessToken(hp, MyAdvapi.TOKEN_READ, hToken)) {
        IntByReference dwSize = new IntByReference();
        MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, null, 0, dwSize);
        {
            Memory pTokenUser = new Memory(dwSize.getValue());
            if (MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, pTokenUser, dwSize.getValue(), dwSize)) {
                MyAdvapi.TOKEN_USER tokenUser = new MyAdvapi.TOKEN_USER(pTokenUser);
                Pointer lpSid = tokenUser.User.Sid;
                Memory lpName = new Memory(256);
                IntByReference cchName = new IntByReference();
                cchName.setValue(256);
                Memory lpReferencedDomainName = new Memory(256);
                IntByReference cchReferencedDomainName = new IntByReference();
                cchReferencedDomainName.setValue(256);
                IntByReference peUse = new IntByReference();
                if (MyAdvapi.INSTANCE.LookupAccountSidW(null, lpSid, lpName, cchName, lpReferencedDomainName, cchReferencedDomainName, peUse))
                    result._user = lpReferencedDomainName.getString(0, true) + "\\" + lpName.getString(0, true);
                ;
            // System.out.println(result._user);
            }
        }
        if (result._user == null)
            System.out.println("could not get user name OS error #" + MyKernel32.INSTANCE.GetLastError());
        MyKernel32.INSTANCE.CloseHandle(hToken.getValue());
    }
    return result;
}
Example 17
Project: JAutoItX-master  File: Process.java View source code
/**
	 * Get the priority of a process.
	 * 
	 * @param pid
	 *            The PID of the process to check.
	 * @return Return the priority of the process if success, return null if
	 *         failed.
	 */
public static ProcPriority getPriority(final int pid) {
    ProcPriority procPriority = null;
    if ((pid > 0) && exists(pid)) {
        HANDLE handle = Kernel32.INSTANCE.OpenProcess(0x0400, false, pid);
        if (handle != null) {
            int priority = Kernel32Ext.INSTANCE.GetPriorityClass(handle);
            switch(priority) {
                case IDLE_PRIORITY_CLASS:
                    procPriority = ProcPriority.LOW;
                    break;
                case BELOW_NORMAL_PRIORITY_CLASS:
                    procPriority = ProcPriority.BELOW_NORMAL;
                    break;
                case NORMAL_PRIORITY_CLASS:
                    procPriority = ProcPriority.NORMAL;
                    break;
                case ABOVE_NORMAL_PRIORITY_CLASS:
                    procPriority = ProcPriority.ABOVE_NORMAL;
                    break;
                case HIGH_PRIORITY_CLASS:
                    procPriority = ProcPriority.HIGH;
                    break;
                case REALTIME_PRIORITY_CLASS:
                    procPriority = ProcPriority.REALTIME;
                    break;
            }
        }
    }
    return procPriority;
}
Example 18
Project: yajsw-master  File: WindowsXPProcess.java View source code
/**
	 * Gets the process.
	 * 
	 * @param pid
	 *            the pid
	 * 
	 * @return the process
	 */
public static Process getProcess(int pid) {
    WindowsXPProcess result = new WindowsXPProcess();
    HANDLE hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_ALL_ACCESS, false, pid);
    if (hProcess == null)
        hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_QUERY_INFORMATION, false, pid);
    if (hProcess == null)
        return null;
    result._pid = pid;
    result._processInformation = new PROCESS_INFORMATION();
    result._processInformation.dwProcessId = pid;
    result._processInformation.hProcess = hProcess;
    result._cmd = result.getCommandLineInternal();
    // on win64 PEB of 64 bit cannot be accessed from wow -> use wmi
    if (result._cmd.equals("?"))
        result._cmd = result.getCommandLineInternalWMI();
    if ("?".equals(result._cmd)) {
        System.err.println("Could not get commandline");
    } else
        System.out.println("Command line of " + pid + ": " + result._cmd);
    PointerByReference hToken = new PointerByReference();
    HANDLE hp = new HANDLE();
    hp.setPointer(hProcess.getPointer());
    if (MyAdvapi.INSTANCE.OpenProcessToken(hp, MyAdvapi.TOKEN_READ, hToken)) {
        IntByReference dwSize = new IntByReference();
        MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, null, 0, dwSize);
        {
            Memory pTokenUser = new Memory(dwSize.getValue());
            if (MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, pTokenUser, dwSize.getValue(), dwSize)) {
                MyAdvapi.TOKEN_USER tokenUser = new MyAdvapi.TOKEN_USER(pTokenUser);
                Pointer lpSid = tokenUser.User.Sid;
                Memory lpName = new Memory(256);
                IntByReference cchName = new IntByReference();
                cchName.setValue(256);
                Memory lpReferencedDomainName = new Memory(256);
                IntByReference cchReferencedDomainName = new IntByReference();
                cchReferencedDomainName.setValue(256);
                IntByReference peUse = new IntByReference();
                if (MyAdvapi.INSTANCE.LookupAccountSidW(null, lpSid, lpName, cchName, lpReferencedDomainName, cchReferencedDomainName, peUse))
                    result._user = lpReferencedDomainName.getString(0, true) + "\\" + lpName.getString(0, true);
                ;
            // System.out.println(result._user);
            }
        }
        if (result._user == null)
            System.out.println("could not get user name OS error #" + MyKernel32.INSTANCE.GetLastError());
        MyKernel32.INSTANCE.CloseHandle(hToken.getValue());
    }
    return result;
}
Example 19
Project: yajsw-maven-master  File: WindowsXPProcess.java View source code
/**
	 * Gets the process.
	 * 
	 * @param pid
	 *            the pid
	 * 
	 * @return the process
	 */
public static Process getProcess(int pid) {
    WindowsXPProcess result = new WindowsXPProcess();
    HANDLE hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_ALL_ACCESS, false, pid);
    if (hProcess == null)
        hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_QUERY_INFORMATION, false, pid);
    if (hProcess == null)
        return null;
    result._pid = pid;
    result._processInformation = new PROCESS_INFORMATION();
    result._processInformation.dwProcessId = pid;
    result._processInformation.hProcess = hProcess;
    result._cmd = result.getCommandLineInternal();
    // on win64 PEB of 64 bit cannot be accessed from wow -> use wmi
    if (result._cmd.equals("?"))
        result._cmd = result.getCommandLineInternalWMI();
    if ("?".equals(result._cmd)) {
        System.err.println("Could not get commandline");
    }
    //else
    //	System.out.println("Command line of " + pid + ": " + result._cmd);
    PointerByReference hToken = new PointerByReference();
    HANDLE hp = new HANDLE();
    hp.setPointer(hProcess.getPointer());
    if (MyAdvapi.INSTANCE.OpenProcessToken(hp, MyAdvapi.TOKEN_READ, hToken)) {
        IntByReference dwSize = new IntByReference();
        MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, null, 0, dwSize);
        {
            Memory pTokenUser = new Memory(dwSize.getValue());
            if (MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, pTokenUser, dwSize.getValue(), dwSize)) {
                MyAdvapi.TOKEN_USER tokenUser = new MyAdvapi.TOKEN_USER(pTokenUser);
                Pointer lpSid = tokenUser.User.Sid;
                Memory lpName = new Memory(256);
                IntByReference cchName = new IntByReference();
                cchName.setValue(256);
                Memory lpReferencedDomainName = new Memory(256);
                IntByReference cchReferencedDomainName = new IntByReference();
                cchReferencedDomainName.setValue(256);
                IntByReference peUse = new IntByReference();
                if (MyAdvapi.INSTANCE.LookupAccountSidW(null, lpSid, lpName, cchName, lpReferencedDomainName, cchReferencedDomainName, peUse))
                    result._user = lpReferencedDomainName.getString(0, true) + "\\" + lpName.getString(0, true);
                ;
            // System.out.println(result._user);
            }
        }
        if (result._user == null)
            System.out.println("could not get user name OS error #" + MyKernel32.INSTANCE.GetLastError());
        MyKernel32.INSTANCE.CloseHandle(hToken.getValue());
    }
    return result;
}
Example 20
Project: yajsw-maven-mk2-master  File: WindowsXPProcess.java View source code
/**
	 * Gets the process.
	 * 
	 * @param pid
	 *            the pid
	 * 
	 * @return the process
	 */
public static Process getProcess(int pid) {
    WindowsXPProcess result = new WindowsXPProcess();
    HANDLE hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_ALL_ACCESS, false, pid);
    if (hProcess == null)
        hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_QUERY_INFORMATION, false, pid);
    if (hProcess == null)
        return null;
    result._pid = pid;
    result._processInformation = new PROCESS_INFORMATION();
    result._processInformation.dwProcessId = pid;
    result._processInformation.hProcess = hProcess;
    result._cmd = result.getCommandLineInternal();
    // on win64 PEB of 64 bit cannot be accessed from wow -> use wmi
    if (result._cmd.equals("?"))
        result._cmd = result.getCommandLineInternalWMI();
    if ("?".equals(result._cmd)) {
        System.err.println("Could not get commandline");
    }
    //else
    //	System.out.println("Command line of " + pid + ": " + result._cmd);
    PointerByReference hToken = new PointerByReference();
    HANDLE hp = new HANDLE();
    hp.setPointer(hProcess.getPointer());
    if (MyAdvapi.INSTANCE.OpenProcessToken(hp, MyAdvapi.TOKEN_READ, hToken)) {
        IntByReference dwSize = new IntByReference();
        MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, null, 0, dwSize);
        {
            Memory pTokenUser = new Memory(dwSize.getValue());
            if (MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, pTokenUser, dwSize.getValue(), dwSize)) {
                MyAdvapi.TOKEN_USER tokenUser = new MyAdvapi.TOKEN_USER(pTokenUser);
                Pointer lpSid = tokenUser.User.Sid;
                Memory lpName = new Memory(256);
                IntByReference cchName = new IntByReference();
                cchName.setValue(256);
                Memory lpReferencedDomainName = new Memory(256);
                IntByReference cchReferencedDomainName = new IntByReference();
                cchReferencedDomainName.setValue(256);
                IntByReference peUse = new IntByReference();
                if (MyAdvapi.INSTANCE.LookupAccountSidW(null, lpSid, lpName, cchName, lpReferencedDomainName, cchReferencedDomainName, peUse))
                    result._user = lpReferencedDomainName.getString(0, true) + "\\" + lpName.getString(0, true);
                ;
            // System.out.println(result._user);
            }
        }
        if (result._user == null)
            System.out.println("could not get user name OS error #" + MyKernel32.INSTANCE.GetLastError());
        MyKernel32.INSTANCE.CloseHandle(hToken.getValue());
    }
    return result;
}