Java 类com.sun.jna.platform.win32.Kernel32 实例源码

项目:IO    文件:DeviceManager.java   
private long getDiskSize(Disk disk) {
    long result = -1l;
    Kernel32 kernel32 = Kernel32.INSTANCE;
    HANDLE diskHandle = kernel32.CreateFile(disk.path, WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, null,
            WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null);
    if (WinBase.INVALID_HANDLE_VALUE.equals(diskHandle)) {
        return result;
    }
    try {
        Memory output = new Memory(Native.getNativeSize(LARGE_INTEGER.class));
        IntByReference lpBytes = new IntByReference();
        boolean success = kernel32.DeviceIoControl(diskHandle,
                WinioctlUtil.CTL_CODE(Winioctl.FILE_DEVICE_DISK, 0x17, Winioctl.METHOD_BUFFERED,
                        Winioctl.FILE_READ_ACCESS),
                null, 0, output, Native.getNativeSize(LARGE_INTEGER.class), lpBytes, null);
        // TODO: Check success?
        result = output.getLong(0);
    }
    finally {
        Kernel32Util.closeHandle(diskHandle);
    }
    return result;
}
项目:Clipcon-Client    文件:Elevator.java   
public static void executeAsAdmin(String command, String args) {
    SHELLEXECUTEINFO execInfo = new SHELLEXECUTEINFO();
    execInfo.lpFile = new WString(command);
    if (args != null) {
        execInfo.lpParameters = new WString(args);
    }
    execInfo.nShow = Shell32X.SW_SHOWDEFAULT;
    execInfo.fMask = Shell32X.SEE_MASK_NOCLOSEPROCESS;
    execInfo.lpVerb = new WString("runas");
    boolean result = Shell32X.INSTANCE.ShellExecuteEx(execInfo);

    if (!result) {
        int lastError = Kernel32.INSTANCE.GetLastError();
        String errorMessage = Kernel32Util.formatMessageFromLastErrorCode(lastError);
        throw new RuntimeException("Error performing elevation: " + lastError + ": " + errorMessage + " (apperror=" + execInfo.hInstApp + ")");
    }
}
项目:NanoUI    文件:TaskBar.java   
private void createHotKeys() {
    Thread keys = new Thread(() -> {
        keysThreadID = Kernel32.INSTANCE.GetCurrentThreadId();
        User32.INSTANCE.RegisterHotKey(new HWND(Pointer.NULL), 1, MOD_WIN | MOD_NOREPEAT, VK_E);
        MSG msg = new MSG();
        while (User32.INSTANCE.GetMessage(msg, new HWND(Pointer.NULL), 0, 0) != 0 && running) {
            if (msg.message == WM_HOTKEY) {
                try {
                    switch (msg.wParam.intValue()) {
                    case 1:
                        new ProcessBuilder("explorer.exe", ",").start();
                        break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        User32.INSTANCE.UnregisterHotKey(Pointer.NULL, 1);
    });
    keys.start();
}
项目:nifi-registry    文件:OSUtils.java   
/**
 * @param process NiFi Registry Process Reference
 * @param logger  Logger Reference for Debug
 * @return        Returns pid or null in-case pid could not be determined
 * This method takes {@link Process} and {@link Logger} and returns
 * the platform specific Handle for Win32 Systems, a.k.a <b>pid</b>
 * In-case it fails to determine the pid, it will return Null.
 * Purpose for the Logger is to log any interaction for debugging.
 */
private static Long getWindowsProcessId(final Process process, final Logger logger) {
    /* determine the pid on windows plattforms */
    try {
        Field f = process.getClass().getDeclaredField("handle");
        f.setAccessible(true);
        long handl = f.getLong(process);

        Kernel32 kernel = Kernel32.INSTANCE;
        WinNT.HANDLE handle = new WinNT.HANDLE();
        handle.setPointer(Pointer.createConstant(handl));
        int ret = kernel.GetProcessId(handle);
        logger.debug("Detected pid: {}", ret);
        return Long.valueOf(ret);
    } catch (final IllegalAccessException | NoSuchFieldException nsfe) {
        logger.debug("Could not find PID for child process due to {}", nsfe);
    }
    return null;
}
项目:ui-automation    文件:Utils.java   
/**
 * Finds the given process in the process list.
 *
 * @param processEntry The process entry.
 * @param filenamePattern pattern matching the filename of the process.
 * @return The found process entry.
 */
public static boolean findProcessEntry
                (final Tlhelp32.PROCESSENTRY32.ByReference processEntry,
                 final Pattern filenamePattern) {
    Kernel32 kernel32 = Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);

    WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));

    boolean found = false;

    try {
        while (kernel32.Process32Next(snapshot, processEntry)) {
            String fname = Native.toString(processEntry.szExeFile);

            if (fname != null && filenamePattern.matcher(fname).matches()) {
                found = true;
                break;
            }
        }
    } finally {
        kernel32.CloseHandle(snapshot);
    }

    return found;
}
项目:yajsw    文件:FileUtils.java   
public static long freeSpace(File file)
{
    if (!file.isDirectory() || !file.exists())
        return -2;

    WinNT.LARGE_INTEGER.ByReference lpTotalNumberOfFreeBytes = new WinNT.LARGE_INTEGER.ByReference();
    lpTotalNumberOfFreeBytes.clear();

    boolean ret = Kernel32.INSTANCE.GetDiskFreeSpaceEx(file.getPath(),
            null, null, lpTotalNumberOfFreeBytes);
    if (ret)
        return lpTotalNumberOfFreeBytes.getValue();
    else
    {
        String s = Kernel32Util
                .formatMessageFromLastErrorCode(Kernel32.INSTANCE
                        .GetLastError());
        log.severe("error in File.freeSpace getting for \""
                + file.getPath() + "\" " + s);
    }

    return -1;
}
项目:yajsw    文件:FileUtils.java   
public static long totalSpace(File file)
{
    if (!file.isDirectory() || !file.exists())
        return -2;

    WinNT.LARGE_INTEGER.ByReference lpTotalNumberOfBytes = new WinNT.LARGE_INTEGER.ByReference();
    lpTotalNumberOfBytes.clear();

    boolean ret = Kernel32.INSTANCE.GetDiskFreeSpaceEx(file.getPath(),
            null, lpTotalNumberOfBytes, null);
    if (ret)
        return lpTotalNumberOfBytes.getValue();
    else
    {
        String s = Kernel32Util
                .formatMessageFromLastErrorCode(Kernel32.INSTANCE
                        .GetLastError());
        log.severe("error in File.totalSpace getting for \""
                + file.getPath() + "\" " + s);
    }

    return -1;

}
项目:yajsw    文件:WindowsXPSystemInformation.java   
private void calc()
{
    if (System.currentTimeMillis() - _lastCall < 500)
        return;
    WinBase.MEMORYSTATUSEX lpBuffer = new WinBase.MEMORYSTATUSEX();
    lpBuffer.dwLength = new DWORD(lpBuffer.size());
    if (Kernel32.INSTANCE.GlobalMemoryStatusEx(lpBuffer))
    {
        lpBuffer.read();
        _freeRAM = lpBuffer.ullAvailPhys.longValue();
        _totalRAM = lpBuffer.ullTotalPhys.longValue();
        _lastCall = System.currentTimeMillis();
    }
    else
    {
        if (_logger != null)
            _logger.severe("ERROR: could not read free/total RAM");
        else
            System.out.println("ERROR: could not read free/total RAM");
    }

}
项目:proxy-vole    文件:WTypes2.java   
/**
 * Memory disposal.
 *
 * @throws Throwable
 */
@Override
protected void finalize() throws Throwable {
    try {
        // Free the memory occupied by the string returned
        // from the Win32 function.
        Pointer strPointer = getPointerToString();
        if (strPointer != null) {
            Pointer result = Kernel32.INSTANCE.GlobalFree(strPointer);
            if (result != null) {
                // The call to GlobalFree has failed. This should never
                // happen. If it really does happen, there isn't much we 
                // can do about it other than logging it.
                Logger.log(getClass(), Logger.LogLevel.ERROR,
                        "Windows function GlobalFree failed while freeing memory for {0} object", 
                        getClass().getSimpleName());
            }
        }
    } finally {
        // This will free the memory of the pointer-to-pointer
        super.finalize();
    }
}
项目:DigitalMediaServer    文件:ProcessManager.java   
/**
 * Retrieves the process ID (PID) for the specified {@link Process}.
 *
 * @param process the {@link Process} for whose PID to retrieve.
 * @return The PID or zero if the PID couldn't be retrieved.
 */
public static int getProcessId(@Nullable Process process) {
    if (process == null) {
        return 0;
    }
    try {
        Field field;
        if (Platform.isWindows()) {
            field = process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            int pid = Kernel32.INSTANCE.GetProcessId(new HANDLE(new Pointer(field.getLong(process))));
            if (pid == 0 && LOGGER.isDebugEnabled()) {
                int lastError = Kernel32.INSTANCE.GetLastError();
                LOGGER.debug("KERNEL32.getProcessId() failed with error {}", lastError);
            }
            return pid;
        }
        field = process.getClass().getDeclaredField("pid");
        field.setAccessible(true);
        return field.getInt(process);
    } catch (Exception e) {
        LOGGER.warn("Failed to get process id for process \"{}\": {}", process, e.getMessage());
        LOGGER.trace("", e);
        return 0;
    }
}
项目:intellij-ce-playground    文件:NativeFileManager.java   
public boolean terminate() {
  Kernel32.HANDLE process = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_TERMINATE | WinNT.SYNCHRONIZE, false, pid);
  if (process.getPointer() == null) {
    Runner.logger.warn("Unable to find process " + name + "(" + pid + ")");
    return false;
  } else {
    Kernel32.INSTANCE.TerminateProcess(process, 1);
    int wait = Kernel32.INSTANCE.WaitForSingleObject(process, 1000);
    if (wait != WinBase.WAIT_OBJECT_0) {
      Runner.logger.warn("Timed out while waiting for process " + name + "(" + pid + ") to end");
      return false;
    }
    Kernel32.INSTANCE.CloseHandle(process);
    return true;
  }
}
项目:intellij-ce-playground    文件:WinProcessManager.java   
/**
 * Returns {@code pid} for Windows process
 * @param process Windows process
 * @return pid of the {@code process}
 */
public static int getProcessPid(Process process) {
  if (process.getClass().getName().equals("java.lang.Win32Process") ||
      process.getClass().getName().equals("java.lang.ProcessImpl")) {
    try {
      long handle = ReflectionUtil.getField(process.getClass(), process, long.class, "handle");

      Kernel32 kernel = Kernel32.INSTANCE;
      WinNT.HANDLE winHandle = new WinNT.HANDLE();
      winHandle.setPointer(Pointer.createConstant(handle));
      return kernel.GetProcessId(winHandle);
    } catch (Throwable e) {
      throw new IllegalStateException(e);
    }
  } else {
    throw new IllegalStateException("Unknown Process implementation");
  }
}
项目:mmf4j    文件:MemoryMapWindows.java   
@Override
protected void _openFile(String path) throws IOException {
    if (file != null) {
        throw new IllegalStateException("The file is already open!");
    }

    file = Kernel32.INSTANCE.CreateFile(
        path,
        WinNT.GENERIC_WRITE + WinNT.GENERIC_READ,
        WinNT.FILE_SHARE_READ,
        null,
        WinNT.OPEN_ALWAYS,
        WinNT.FILE_ATTRIBUTE_NORMAL,
        null);
    if (WinNT.INVALID_HANDLE_VALUE.equals(file)) {
        throw new IOException("Unable to open file: " + getLastErrorAsString());
    }
}
项目:mmf4j    文件:MemoryMapWindows.java   
@Override
protected void _openMapping(long size) throws IOException {
    if (mapping != null) {
        throw new IllegalStateException("File is already mapped!");
    }

    mapping = Kernel32.INSTANCE.CreateFileMapping(
        file,
        null,
        WinNT.PAGE_READWRITE,
        (int) (size >> 8 * 4),
        (int) (size & 0xFFFFFFFFL),
        null);

    if (mapping == null || WinNT.INVALID_HANDLE_VALUE.equals(mapping)) {
        throw new IOException("Unable to map file: " + getLastErrorAsString());
    } else if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_ALREADY_EXISTS) {
        //File mapping already existing, TODO how to care about?
        throw new IOException("ERROR_ALREADY_EXISTS, don't know how to handle that!");
    }
}
项目:mmf4j    文件:MemoryMapWindows.java   
@Override
protected void _truncateFile(long size) throws IOException {
    // TODO Handle lp of size
    int resSFP = MMFKernel32.INSTANCE.SetFilePointer(file, size, Pointer.NULL, 1);
    if (WinBase.INVALID_SET_FILE_POINTER == resSFP) {
        throw new IOException("INVALID_SET_FILE_POINTER: " + Kernel32.INSTANCE.GetLastError());
    }

    Kernel32.INSTANCE.CloseHandle(mapping);
    mapping = null;

    boolean resSEOF = MMFKernel32.INSTANCE.SetEndOfFile(file);
    if (!resSEOF) {
        throw new IOException(
            "Unable to SetEndOfFile: " + getLastErrorAsString());
    }
}
项目:me3modmanager    文件:ModManager.java   
/**
 * Checks if MassEffect3.exe is currently running. Uses native code.
 * 
 * @return
 */
public static boolean isMassEffect3Running() {
    try {
        Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
        Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
        boolean result = false;
        WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
        try {
            while (kernel32.Process32Next(snapshot, processEntry)) {
                if ("MassEffect3.exe".toUpperCase().equals(Native.toString(processEntry.szExeFile).toUpperCase())) {
                    result = true;
                    break;
                }
            }
        } finally {
            kernel32.CloseHandle(snapshot);
        }
        ModManager.debugLogger.writeMessage("Mass Effect 3 is " + (result ? "" : "not ") + "currently running.");
        return result;
    } catch (Throwable t) {
        ModManager.debugLogger.writeErrorWithException("Critical native access exception: ", t);
        ModManager.debugLogger.writeError("Mod Manager will report that the game is not running to continue normal operations.");
        return false;
    }
}
项目:Java-Auto-Update    文件:WindowsProcessExecutor.java   
@Override
public String findProcessId(Process process) throws NoSuchFieldException, IllegalAccessException {
    if (process.getClass().getName().equals("java.lang.Win32Process")
            || process.getClass().getName().equals("java.lang.ProcessImpl")) {
            Field f = process.getClass().getDeclaredField("handle");
            f.setAccessible(true);
            long handleNumber = f.getLong(process);

            Kernel32 kernel = Kernel32.INSTANCE;
            WinNT.HANDLE handle = new WinNT.HANDLE();
            handle.setPointer(Pointer.createConstant(handleNumber));
            int pid = kernel.GetProcessId(handle);
            log.debug("Found pid for managed process: {}", pid);
            return pid + "";
    }
    return null;
}
项目:jpexs-decompiler    文件:Win32ProcessTools.java   
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;
}
项目:jpexs-decompiler    文件:CommandLineArgumentParser.java   
private static void parseAffinity(Stack<String> args) {
    if (Platform.isWindows()) {
        if (args.isEmpty()) {
            System.err.println("affinity parameter expected");
            badArguments("affinity");
        }
        try {
            int affinityMask = Integer.parseInt(args.pop());
            Kernel32.INSTANCE.SetProcessAffinityMask(Kernel32.INSTANCE.GetCurrentProcess(), affinityMask);
        } catch (NumberFormatException nex) {
            System.err.println("Bad affinityMask value");
        }
    } else {
        System.err.println("Process affinity setting is only available on Windows platform.");
    }
}
项目:sheepit-client    文件:WinProcess.java   
private List<WinProcess> getChildren() throws IOException {
    ArrayList<WinProcess> result = new ArrayList<WinProcess>();

    WinNT.HANDLE hSnap = this.kernel32lib.CreateToolhelp32Snapshot(Kernel32Lib.TH32CS_SNAPPROCESS, new DWORD(0));
    Kernel32Lib.PROCESSENTRY32.ByReference ent = new Kernel32Lib.PROCESSENTRY32.ByReference();
    if (!this.kernel32lib.Process32First(hSnap, ent)) {
        return result;
    }
    do {
        if (ent.th32ParentProcessID.intValue() == this.pid) {
            try {
                result.add(new WinProcess(ent.th32ProcessID.intValue()));
            }
            catch (IOException e) {
                System.err.println("WinProcess::getChildren, IOException " + e);
            }
        }
    }
    while (this.kernel32lib.Process32Next(hSnap, ent));

    Kernel32.INSTANCE.CloseHandle(hSnap);

    return result;
}
项目:buck    文件:ProcessHelper.java   
@Nullable
private Long windowsProcessId(Object process) {
  Class<?> clazz = process.getClass();
  if (clazz.getName().equals("java.lang.Win32Process")
      || clazz.getName().equals("java.lang.ProcessImpl")) {
    try {
      Field f = clazz.getDeclaredField("handle");
      f.setAccessible(true);
      long peer = f.getLong(process);
      Pointer pointer = Pointer.createConstant(peer);
      WinNT.HANDLE handle = new WinNT.HANDLE(pointer);
      return (long) Kernel32.INSTANCE.GetProcessId(handle);
    } catch (Exception e) {
      LOG.warn(e, "Cannot get process id!");
    }
  }
  return null;
}
项目:proactive-component-monitoring    文件:WindowsProcess.java   
/**
 * Kill a process from its PID.
 * 
 * @param pid the PID
 * @param code the code
 * @return true, if successful
 */
public static boolean kill(final int pid, final int code) {
    if (pid <= 0) {
        return false;
    }
    final HANDLE hProcess = Kernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_TERMINATE, false, pid);
    if (hProcess == null) {
        win32ErrorRuntime("OpenProcess");
    }
    boolean result = false;
    try {
        result = Kernel32.INSTANCE.TerminateProcess(hProcess, code);
        if (!result) {
            win32ErrorRuntime("TerminateProcess");
        }
    } finally {
        Kernel32.INSTANCE.CloseHandle(hProcess);
    }
    return result;
}
项目:pty4j    文件:NamedPipe.java   
private synchronized boolean closeImpl() {
  if (shutdownFlag) {
    // If shutdownFlag is already set, then the handles are already closed.
    return false;
  }
  shutdownFlag = true;
  Kernel32.INSTANCE.SetEvent(shutdownEvent);
  if (!myFinalizedFlag) {
    readLock.lock();
    writeLock.lock();
    writeLock.unlock();
    readLock.unlock();
  }
  Kernel32.INSTANCE.CloseHandle(shutdownEvent);
  Kernel32.INSTANCE.CloseHandle(readEvent);
  Kernel32.INSTANCE.CloseHandle(writeEvent);
  return true;
}
项目:consulo    文件:WinProcessManager.java   
public static int getProcessId(Process process) {
  String processClassName = process.getClass().getName();
  if (processClassName.equals("java.lang.Win32Process") || processClassName.equals("java.lang.ProcessImpl")) {
    try {
      if (SystemInfo.IS_AT_LEAST_JAVA9) {
        //noinspection JavaReflectionMemberAccess
        return ((Long)Process.class.getMethod("pid").invoke(process)).intValue();
      }

      long handle = assertNotNull(ReflectionUtil.getField(process.getClass(), process, long.class, "handle"));
      return Kernel32.INSTANCE.GetProcessId(new WinNT.HANDLE(Pointer.createConstant(handle)));
    }
    catch (Throwable t) {
      throw new IllegalStateException("Failed to get PID from instance of " + process.getClass() + ", OS: " + SystemInfo.OS_NAME, t);
    }
  }

  throw new IllegalStateException("Unable to get PID from instance of " + process.getClass() + ", OS: " + SystemInfo.OS_NAME);
}
项目:BEAST    文件:Win32Process.java   
/**
 * creates a new Win32 Process given a process id
 * @param pid the process id that describes this process
 * @throws IOException if something goes wrong with creating the process reference
 */
public Win32Process(int pid) throws IOException
{
    handle = Kernel32.INSTANCE.OpenProcess(
            0x0400 | /* PROCESS_QUERY_INFORMATION */
            0x0800 | /* PROCESS_SUSPEND_RESUME */
            0x0001 | /* PROCESS_TERMINATE */
            0x00100000 /* SYNCHRONIZE */,
            false,
            pid);
    if (handle == null) 
        throw new IOException("OpenProcess failed: " 
    + Kernel32Util.formatMessageFromLastErrorCode(Kernel32.INSTANCE.GetLastError()));
    this.pid = pid;
}
项目:Nird2    文件:WindowsRemovableDriveFinder.java   
@Override
public Collection<File> findRemovableDrives() throws IOException {
    File[] roots = File.listRoots();
    if (roots == null) throw new IOException();
    List<File> drives = new ArrayList<>();
    for (File root : roots) {
        try {
            int type = Kernel32.INSTANCE.GetDriveType(root.getPath());
            if (type == DRIVE_REMOVABLE) drives.add(root);
        } catch (RuntimeException e) {
            throw new IOException(e);
        }
    }
    return drives;
}
项目:Nird2    文件:WindowsRemovableDriveFinder.java   
@Override
public Collection<File> findRemovableDrives() throws IOException {
    File[] roots = File.listRoots();
    if (roots == null) throw new IOException();
    List<File> drives = new ArrayList<>();
    for (File root : roots) {
        try {
            int type = Kernel32.INSTANCE.GetDriveType(root.getPath());
            if (type == DRIVE_REMOVABLE) drives.add(root);
        } catch (RuntimeException e) {
            throw new IOException(e);
        }
    }
    return drives;
}
项目:NanoUI    文件:Util.java   
public static String getAppUserModelId(HWND hwnd) {
    IntByReference processID = new IntByReference();
    User32.INSTANCE.GetWindowThreadProcessId(hwnd, processID);
    HANDLE hProcess = Kernel32.INSTANCE.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processID.getValue());
    UINTByReference length = new UINTByReference();
    Kernel32Ext.INSTANCE.GetApplicationUserModelId(hProcess, length, null);
    char[] modelID = new char[length.getValue().intValue()];
    Kernel32Ext.INSTANCE.GetApplicationUserModelId(hProcess, length, modelID);
    return new String(Native.toString(modelID));
}
项目:ui-automation    文件:Utils.java   
private static void ensureWinApiInstances() {
    if (user32 == null) {
           user32 = User32.INSTANCE;
       }
    if (kernel32 == null) {
        kernel32 = Kernel32.INSTANCE;
       }
}
项目:ui-automation    文件:AutomationWindow.java   
/**
 * Sets transparency of the window.
 * @param alpha 0..255 alpha attribute.
 * @throws Win32Exception WIN32 call has failed.
 * @throws AutomationException Something is wrong in automation.
 */
public void setTransparency(int alpha) throws Win32Exception, AutomationException {
    WinDef.HWND hwnd = this.getNativeWindowHandle();

    if (user32.SetWindowLong(hwnd, User32.GWL_EXSTYLE, User32.WS_EX_LAYERED) == 0) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }

    if (!user32.SetLayeredWindowAttributes(hwnd, 0, (byte)alpha, User32.LWA_ALPHA)) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
}
项目:yajsw    文件:WindowsXPMouse.java   
public WindowsXPMouse()
{
    if (!Platform.isWindows())
    {
        throw new UnsupportedOperationException(
                "Not supported on this platform.");
    }
    USER32INST = User32.INSTANCE;
    KERNEL32INST = Kernel32.INSTANCE;
    mouseHook = hookTheMouse();
    Native.setProtected(true);

}
项目:yajsw    文件:WindowsXPProcess.java   
private static void setShutdownPrivileges() {
    final WinNT.HANDLEByReference token = new WinNT.HANDLEByReference();
    Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), WinNT.TOKEN_ADJUST_PRIVILEGES, token);

    final WinNT.LUID luid = new WinNT.LUID();
    Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_SHUTDOWN_NAME, luid);

    final WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1);
    tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new WinDef.DWORD(WinNT.SE_PRIVILEGE_ENABLED));
    Advapi32.INSTANCE.AdjustTokenPrivileges(token.getValue(), false, tp, 0, null, new IntByReference(0));
}
项目:DigitalMediaServer    文件:ProcessManager.java   
/**
 * Performs {@code TerminateProcess} on the specified Windows
 * {@link Process}.
 *
 * @param processInfo the {@link ProcessInfo} referencing the
 *            {@link Process} to terminate.
 * @return {@code true} if {@code TerminateProcess} was executed,
 *         {@code false} otherwise.
 */
protected boolean stopWindowsProcessTerminateProcess(@Nonnull ProcessInfo processInfo) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(
            "Attempting to stop timed out process \"{}\" ({}) with TerminateProcess",
            processInfo.getName(),
            processInfo.getPID()
        );
    }
    HANDLE hProc = Kernel32.INSTANCE.OpenProcess(
        Kernel32.PROCESS_TERMINATE,
        false,
        processInfo.getPID()
    );
    if (hProc == null) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(
                "Failed to get Windows handle for process \"{}\" ({}) during TerminateProcess",
                processInfo.getName(),
                processInfo.getPID()
            );
        }
        return false;
    }
    boolean result = Kernel32.INSTANCE.TerminateProcess(hProc, 1);
    Kernel32.INSTANCE.CloseHandle(hProc);
    if (LOGGER.isTraceEnabled()) {
        if (result) {
            LOGGER.trace("TerminateProcess performed for process \"{}\" ({})", processInfo.getName(), processInfo.getPID());
        } else {
            LOGGER.trace("TerminateProcess failed for process \"{}\" ({})", processInfo.getName(), processInfo.getPID());
        }
    }
    return result;
}
项目:MercuryTrade    文件:MainTestKeyHook.java   
public static void main(String[] args) throws Exception {
    HOOKPROC hookProc = new HOOKPROC_bg();
    HINSTANCE hInst = Kernel32.INSTANCE.GetModuleHandle(null);

    User32.HHOOK hHook = User32.INSTANCE.SetWindowsHookEx(User32.WH_KEYBOARD_LL, hookProc, hInst, 0);
    if (hHook == null)
        return;
    User32.MSG msg = new User32.MSG();
    System.err.println("Please press any key ....");
    while (true) {
        User32.INSTANCE.GetMessage(msg, null, 0, 0);
    }
}
项目:ipc-eventbus    文件:Jna.java   
static long getWindowsPid(Process process) {
  if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) {
    try {
      Field f = process.getClass().getDeclaredField("handle");
      f.setAccessible(true);
      long handl = f.getLong(process);
      Kernel32 kernel = Kernel32.INSTANCE;
      WinNT.HANDLE handle = new WinNT.HANDLE();
      handle.setPointer(Pointer.createConstant(handl));
      return kernel.GetProcessId(handle);
    } catch (Throwable ignored) {
    }
  }
  return -1;
}
项目:mmf4j    文件:MemoryMapWindows.java   
@Override
protected Pointer _getViewPointer(long offset, int size) {
    Pointer p = Kernel32.INSTANCE.MapViewOfFile(
        mapping,
        FILE_MAP_READ | FILE_MAP_WRITE,
        (int) (offset >> 8 * 4),
        (int) (offset & 0xFFFFFFFFL),
        size);
    if(p == Pointer.NULL) {
        throw new MemoryMappingException(getLastErrorAsString());
    } else {
        return p;
    }
}
项目:gw2route    文件:GPS.java   
public GPS(CefBrowser pBrowser, Option pOptions)
{
    this.sharedFile = Kernel32.INSTANCE.CreateFileMapping(
            WinBase.INVALID_HANDLE_VALUE, null, WinNT.PAGE_EXECUTE_READWRITE, 0, MEM_MAP_SIZE, MEM_MAP_NAME);
    this.sharedMemory = Kernel32.INSTANCE.MapViewOfFile(
            this.sharedFile, WinNT.SECTION_MAP_READ, 0, 0, MEM_MAP_SIZE);

    this.TheBrowser = pBrowser;
    this.TheOptions = pOptions;
}
项目:briar    文件:WindowsRemovableDriveFinder.java   
public Collection<File> findRemovableDrives() throws IOException {
    File[] roots = File.listRoots();
    if(roots == null) throw new IOException();
    List<File> drives = new ArrayList<File>();
    for(File root : roots) {
        try {
            int type = Kernel32.INSTANCE.GetDriveType(root.getPath());
            if(type == DRIVE_REMOVABLE) drives.add(root);
        } catch(RuntimeException e) {
            throw new IOException(e);
        }
    }
    return Collections.unmodifiableList(drives);
}
项目:JAutoItX    文件:Process.java   
/**
 * 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;
}