对于想了解Win32Error的读者,本文将是一篇不可错过的文章,我们将详细介绍win32error126,并且为您提供关于C:\ProgramFiles\MSBuild\Microsoft.Cpp\
对于想了解Win32 Error的读者,本文将是一篇不可错过的文章,我们将详细介绍win32 error 126,并且为您提供关于C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\Microsoft.Cpp.Win32 .Targets(147,5): error MSB6006:、com.sun.jna.platform.win32.W32Errors的实例源码、com.sun.jna.platform.win32.Win32Exception的实例源码、com.sun.jna.platform.win32.WinError的实例源码的有价值信息。
本文目录一览:- Win32 Error(win32 error 126)
- C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\Microsoft.Cpp.Win32 .Targets(147,5): error MSB6006:
- com.sun.jna.platform.win32.W32Errors的实例源码
- com.sun.jna.platform.win32.Win32Exception的实例源码
- com.sun.jna.platform.win32.WinError的实例源码
Win32 Error(win32 error 126)
一、Win32 错误
也就是 Win32 子系统产生的错误。当我们在自己的代码里调用 Windows 系统的 API 函数,系统执行 API 内部代码,当 API 内部代码出现错误,会将预先定义好的错误代码写到调用这个 API 的线程局部存储区域 (这个区域是每个线程独有的其他线程无法更改。它存储着一些线程独有的东西),然后 API 返回,返回值告诉我们该 API 执行失败了。如果我们的代码加了检测,发现了 API 失败,这时我们调用 GetLastError () 函数去获取这个错误代码,这个错误代码是一个 DWORD 值。如果我们不及时获取,就会被后面调用的 API 所覆盖。当我们想在自己的函数里借用这种机制时,可以调用 SetLastError 函数来设置一个错误代码。
这里我们提到了两个 API:
- DWORD GetLastError(VOID)
- void SetLastError(DWORD dwErrCode)
二、Win32 Error Code
所有 Win32 错误代码都必须在 0x0000 到 0xFFFF 范围内,尽管 Win32 错误代码可以同时用于 16 位字段和 32 位字段,我们通常还是用 32 位来表示。大多数值已经定义了默认错误消息,可用于将值映射到我们可以读懂的文本消息。它的构成如下:
虽然 win32 子系统错误的位域有 32bit, 但受限于值的范围,也只能是 0x00000000---0x0000FFF, 也就是上面的位域高 16bit 都是 0。
通过前面的说明我们了解了错误代码的获取,以及错误代码和信息是怎么制作出来的,那么当我们用GetLastError获取到错误代码后,我们只是有了一个编号,还是不了解具体什么原因什么错误,这时,我们该用到另外一个函数了FormatMessage。
原型:
DWORD
WINAPI FormatMessage (
DWORD
dwFlags,
// source and processing options
LPCVOID
lpSource,
// message source
DWORD
dwMessageId,
// message identifier
DWORD
dwLanguageId,
// language identifier
LPTSTR
lpBuffer,
// message buffer
DWORD
nSize,
// maximum size of message buffer
va_list
*Arguments
// array of message inserts
);
FormatMessage
来查询错误信息,写到我们自己的日志里,来帮助我们调试程序的功能性和业务性问题。
C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\Microsoft.Cpp.Win32 .Targets(147,5): error MSB6006:
node-gyp build 报错
C:\Users\Administrator\Desktop\testc>node-gyp build gyp info it worked if it ends with ok gyp info using node-gyp@3.4.0 gyp info using node@4.4.2 | win32 | ia32 gyp info spawn C:\windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe gyp info spawn args [ ''build/binding.sln'', gyp info spawn args ''/clp:Verbosity=minimal'', gyp info spawn args ''/nologo'', gyp info spawn args ''/p:Configuration=Release;Platform=Win32'' ] 在此解决方案中一次生成一个项目。若要启用并行生成,请添加“/m”开关。 TRACKER : C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\Microsoft.Cpp.Win32 .Targets(147,5): error MSB6006: “CL.exe”已退出,代码为 5。 [C:\Users\Administr ator\Desk top\testc\build\hello.vcxproj] gyp ERR! build error gyp ERR! stack Error: `C:\windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe ` failed with exit code: 1 gyp ERR! stack at ChildProcess.onExit (C:\Users\Administrator\AppData\Roamin g\npm\node_modules\node-gyp\lib\build.js:276:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit (events.js:172:7) gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_proces s.js:200:12) gyp ERR! System Windows_NT 6.1.7601 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Administrator \\AppData\\Roaming\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "build" gyp ERR! cwd C:\Users\Administrator\Desktop\testc gyp ERR! node -v v4.4.2 gyp ERR! node-gyp -v v3.4.0 gyp ERR! not ok

http://snoopyxdy.blog.163.com/blog/static/601174402012102391344617/
我运行到 node-gyp build 时就报这个错误,群里没人解决,来这里请教下大神,谢谢!!
com.sun.jna.platform.win32.W32Errors的实例源码
public String resolveFolder(FolderId folderId) { int folder = convertFolderId(folderId); char[] pszPath = new char[WinDef.MAX_PATH]; HRESULT result = Shell32.INSTANCE.SHGetFolderPath(null,folder,null,pszPath); if (W32Errors.S_OK.equals(result)) { return Native.toString(pszPath); } logger.error("SHGetFolderPath returns an error: {}",result.intValue()); throw new AppDirsException( "SHGetFolderPath returns an error: " + result.intValue()); }
/** * @return 0 - color in format 0xAARRGGBB,1 - opaque */ public static int[] DwmGetColorizationColor() { IntByReference colorRef = new IntByReference(); IntByReference opaqueRef = new IntByReference(); WinNT.HRESULT hresult = DwmApi.INSTANCE.DwmGetColorizationColor(colorRef,opaqueRef); if(W32Errors.S_OK.equals(hresult)) { return new int[] {colorRef.getValue(),opaqueRef.getValue()}; } return new int[2]; }
public static boolean DwmIsCompositionEnabled() { IntByReference reference = new IntByReference(); WinNT.HRESULT hresult = INSTANCE.DwmIsCompositionEnabled(reference); return W32Errors.S_OK.equals(hresult) && reference.getValue() == 1; }
com.sun.jna.platform.win32.Win32Exception的实例源码
public static String[] getAvailablebrowsers() throws DebuggableException { try { String[] keys = Advapi32Util.registryGetKeys(WinReg.HKEY_LOCAL_MACHINE,WIN_REG_CLIENTS_PATH); List<String> filteredList = new ArrayList<String>(50); for (int i = 0; i < keys.length; i++) { if (!keys[i].equals(WIN_REG_INTERNET_CLIENT_KEY)) { filteredList.add(keys[i]); } } String[] out = new String[filteredList.size()]; for (int i = 0; i < out.length; i++) { out[i] = filteredList.get(i); } return out; } catch (Win32Exception e) { throw new DebuggableException(null,"(Try&catch try)","Throw debuggable exception","(End of function)","Error reading registry",false,e); } }
private void checkKeyExists( String rootKey,String keyPath,String keyName ) { try { WinReg.HKEY rootHKey = getHKey(rootKey); if (!Advapi32Util.registryValueExists(rootHKey,keyPath,keyName)) { throw new RegistryOperationsException("Registry key does not exist. " + getDescription(rootKey,keyName)); } } catch (Win32Exception e) { throw new RegistryOperationsException("Registry key path does not exist. " + getDescription(rootKey,keyName),e); } }
/** * Captures the window. * * @param hwnd The window to capture. * @param filename Name to save the output into. * @throws AWTException Robot exception. * @throws IOException IO Exception. */ public static void capture(final WinDef.HWND hwnd,final String filename) throws AWTException,IOException,Win32Exception { ensureWinApiInstances(); WinDef.RECT rect = new WinDef.RECT(); if (!user32.GetwindowRect(hwnd,rect)) { throw new Win32Exception(kernel32.GetLastError()); } Rectangle rectangle = new Rectangle(rect.left,rect.top,rect.right -rect.left,rect.bottom -rect.top); BufferedImage image = new Robot().createScreenCapture(rectangle); ImageIO.write(image,"png",new File(filename)); }
@Test(expected= Win32Exception.class) public void test_setTransparency_Throws_Exception_When_Win32_Calls_Throw_Error() throws Exception { doAnswer(invocation -> { Object[] args = invocation.getArguments(); Object reference = (Object)args[0]; reference = 1245; return 1234; }).when(element).getPropertyValue(anyInt()); iuiAutomation mocked_automation = Mockito.mock(iuiAutomation.class); UIAutomation instance = new UIAutomation(mocked_automation); AutomationWindow wndw = new AutomationWindow( new ElementBuilder(element).window(window).itemContainer(container).automation(instance)); wndw.setTransparency(100); verify(element,atLeastOnce()).getPropertyValue(anyInt()); }
/** * Authenticates the user using Windows logonUser API */ @CheckForNull public WindowsPrincipal logonUser(String userName,String password) { checkArgument(isNotEmpty(userName),"userName is null or empty."); checkArgument(isNotEmpty(password),"password is null or empty."); LOG.debug("Authenticating user: {}",userName); WindowsPrincipal windowsPrincipal = null; IWindowsIdentity windowsIdentity = null; try { windowsIdentity = windowsAuthProvider.logonUser(userName,password); if (windowsIdentity != null) { windowsPrincipal = new WindowsPrincipal(windowsIdentity); } } catch (Win32Exception win32Exception) { LOG.debug("User {} is not authenticated : {}",userName,win32Exception.getMessage()); } finally { if (windowsIdentity != null) { windowsIdentity.dispose(); } } return windowsPrincipal; }
private void runlogonUserTest(String userName,String password,boolean islogonUserSuccessful) { IWindowsIdentity windowsIdentity = null; Win32Exception win32Exception = mock(Win32Exception.class); if (islogonUserSuccessful) { windowsIdentity = mock(IWindowsIdentity.class); Mockito.when(windowsIdentity.getFqn()).thenReturn(userName); Mockito.when(windowsIdentity.getGroups()).thenReturn(new IWindowsAccount[0]); Mockito.when(windowsAuthProvider.logonUser(userName,password)).thenReturn(windowsIdentity); } else { Mockito.when(windowsAuthProvider.logonUser(userName,password)).thenThrow(win32Exception); } WindowsPrincipal windowsPrincipal = authenticationHelper.logonUser(userName,password); if (islogonUserSuccessful) { assertthat(windowsPrincipal.getName()).isEqualTo(windowsIdentity.getFqn()); Mockito.verify(windowsIdentity,Mockito.times(1)).dispose(); Mockito.verify(win32Exception,Mockito.times(0)).getMessage(); } else { assertthat(windowsPrincipal).isNull(); Mockito.verify(win32Exception,Mockito.times(1)).getMessage(); } Mockito.verify(windowsAuthProvider,Mockito.times(1)).logonUser(userName,password); }
protected void getVLCRegistryInfo() { String key = "SOFTWARE\\VideoLAN\\VLC"; try { if (!Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE,key)) { key = "SOFTWARE\\Wow6432Node\\VideoLAN\\VLC"; if (!Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE,key)) { return; } } vlcPath = Paths.get(Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE,key,"")); vlcVersion = new Version(Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE,"Version")); } catch (Win32Exception e) { LOGGER.debug("Could not get VLC information from Windows registry: {}",e.getMessage()); LOGGER.trace("",e); } }
protected String getavisynthPluginsFolder() { String key = "SOFTWARE\\avisynth"; try { if (!Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE,key)) { key = "SOFTWARE\\Wow6432Node\\avisynth"; if (!Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE,key)) { return null; } } return Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE,"plugindir2_5"); } catch (Win32Exception e) { LOGGER.debug("Could not get avisynth information from Windows registry: {}",e); } return null; }
protected String getKLiteFiltersFolder() { String key = "SOFTWARE\\Wow6432Node\\KLCodecPack"; try { if (!Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE,key)) { key = "SOFTWARE\\KLCodecPack"; if (!Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE,"installdir"); } catch (Win32Exception e) { LOGGER.debug("Could not get K-Lite Codec Pack information from Windows registry: {}",e); } return null; }
/** * Retrieves the id of the process that belongs to the given exe-file name. * * @param szExeFile * Name of the exe-File. * @return The id of the process that belongs to the given exe-file name or * <tt>0</tt> (zero) if not found. */ public static int getProcessIdBySzExeFile(final String szExeFile) { try { final Iterator<Process> processes = Kernel32Util.getProcessList().iterator(); while (processes.hasNext()) { final Process process = processes.next(); if (process.getSzExeFile().equalsIgnoreCase(szExeFile)) { return process.getPid(); } } } catch (final Win32Exception e) { // Just catch the exception and return an error code } return 0; }
public static String getbrowserValue() { if (SETTINGS.getProperty(KEY_broWSER) == null || SETTINGS.getProperty(KEY_broWSER).isEmpty()) { try { String value = Advapi32Util.registryGetStringValue(APP_ROOT_HKEY,REGISTRY_APP_PATH,KEY_broWSER); return value; } catch (Win32Exception e) { return ApplicationConstants.broWSER_DEFAULT_VALUE; } } else { if (!SETTINGS.getProperty(KEY_broWSER).equals(ApplicationConstants.broWSER_DEFAULT_VALUE)) { return SETTINGS.getProperty(KEY_broWSER); } else { return ApplicationConstants.broWSER_DEFAULT_VALUE; } } }
public static String getInstallLocationValue() throws RegistryCanNotReadInfoException { if (SETTINGS.getProperty(KEY_INSTALL_LOCATION) == null || SETTINGS.getProperty(KEY_INSTALL_LOCATION).isEmpty()) { try { String value = Advapi32Util.registryGetStringValue(APP_ROOT_HKEY,KEY_INSTALL_LOCATION); if (!value.endsWith(File.separator)) { value = value + File.separator; } SETTINGS.setProperty(KEY_INSTALL_LOCATION,value); return value; } catch (Win32Exception e) { throw new RegistryCanNotReadInfoException("Can not read Installed Location value : " + "HKCU\\" + REGISTRY_APP_PATH + "" + KEY_INSTALL_LOCATION,e); } } else return SETTINGS.getProperty(KEY_INSTALL_LOCATION); }
@SuppressWarnings("UnusedReturnValue") public static String getAppNameValue() throws RegistryCanNotReadInfoException { if (SETTINGS.getProperty(KEY_APP_NAME) == null || SETTINGS.getProperty(KEY_APP_NAME).isEmpty()) { try { String value = Advapi32Util.registryGetStringValue(APP_ROOT_HKEY,KEY_APP_NAME); SETTINGS.setProperty(KEY_APP_NAME,value); return value; } catch (Win32Exception e) { throw new RegistryCanNotReadInfoException("Can not read Installed Location value : " + "HKLM\\" + REGISTRY_APP_PATH + "" + KEY_APP_NAME,e); } } else return SETTINGS.getProperty(KEY_APP_NAME); }
@SuppressWarnings("UnusedReturnValue") public static String getURLUpdateValue() throws RegistryCanNotReadInfoException { if (SETTINGS.getProperty(KEY_URL_UPDATE_LINK) == null || SETTINGS.getProperty(KEY_URL_UPDATE_LINK).isEmpty()) { try { String value = Advapi32Util.registryGetStringValue(APP_ROOT_HKEY,KEY_URL_UPDATE_LINK); SETTINGS.setProperty(KEY_URL_UPDATE_LINK,value); return value; } catch (Win32Exception e) { throw new RegistryCanNotReadInfoException( "Can not read Installed Location value : " + "HKLM\\" + REGISTRY_APP_PATH + "" + KEY_URL_UPDATE_LINK,e); } } else return SETTINGS.getProperty(KEY_URL_UPDATE_LINK); }
/** * Check if registry keys exist and if the cmd file the key contains matches the latest cmd file * * @param newCmd * @return if keys exists or not */ protected static boolean doesKeyNeedUpdated(final File newCmd) throws IOException { try { final String existingKey = Advapi32Util.registryGetStringValue(WinReg.HKEY_CURRENT_USER,VSOI_KEY,StringUtils.EMPTY); final File existingCmd = new File(existingKey.replace("\"%1\"","").trim()); if (!existingCmd.exists()) { logger.debug("The registry key needs updated because the old key cmd file doesn't exist."); return true; } if (existingCmd.getPath().equalsIgnoreCase(newCmd.getPath()) || FileUtils.contentEquals(existingCmd,newCmd)) { logger.debug("The registry key does not need updated because {}",existingCmd.getPath().equalsIgnoreCase(newCmd.getPath()) ? "the file paths are the same" : "the contents of the files are the same."); return false; } // use the newest cmd file so update if existing cmd file is older // Todo: version cmd file if we continually iterate on it so we chose the correct file more reliably logger.debug("The existing cmd file is {} old and the the cmd file is {} old",existingCmd.lastModified(),newCmd.lastModified()); return existingCmd.lastModified() < newCmd.lastModified() ? true : false; } catch (Win32Exception e) { // Error occurred reading the registry (possible key doesn't exist or is empty) so update just to be safe logger.debug("There was an issue reading the registry so updating the key to be safe."); return true; } }
/** * Fetches the full backup path from the registry. * * @return Filepath from registry to full backup path. If none exists,this * returns null. */ public static String GetFullBackupPath(boolean returnEvenIfInvalid) { String backupPath = null; try { backupPath = Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER,VanillaUserRegistryKey,VanillaUserRegistryValue); File backupDir = new File(backupPath); if (verifyVanillaBackup(backupDir)) { ModManager.debugLogger.writeMessage("Found valid vanilla copy location in registry: " + backupPath); } else { ModManager.debugLogger.writeError("Found vanilla copy location in registry,but it doesn't seem to be valid,at least one of the validation checks Failed"); } } catch (Win32Exception e) { ModManager.debugLogger.writeErrorWithException("Win32Exception reading registry - assuming no backup exists yet (this is not really an error... mostly).",e); } if (backupPath != null) { if (new File(backupPath).exists() && new File(backupPath).isDirectory()) { return backupPath; } else if (returnEvenIfInvalid) { ModManager.debugLogger.writeError("returnEvenIfInvalid - returning path anyways."); return backupPath; } } return null; }
/** * Returns the osu! installation directory. * @return the directory,or null if not found */ private static File getosuInstallationDirectory() { if (!System.getProperty("os.name").startsWith("Win")) return null; // only works on Windows // registry location final WinReg.HKEY rootKey = WinReg.HKEY_CLASSES_ROOT; final String regKey = "osu\\DefaultIcon"; final String regValue = null; // default value final String regPathPattern = "\"(.+)\\\\[^\\/]+\\.exe\""; String value; try { value = Advapi32Util.registryGetStringValue(rootKey,regKey,regValue); } catch (Win32Exception e) { return null; // key/value not found } Pattern pattern = Pattern.compile(regPathPattern); Matcher m = pattern.matcher(value); if (!m.find()) return null; File dir = new File(m.group(1)); return (dir.isDirectory()) ? dir : null; }
public static boolean isAddedToContextMenu() { if (!Platform.isWindows()) { return false; } final WinReg.HKEY REG_CLASSES_HKEY = WinReg.HKEY_LOCAL_MACHINE; final String REG_CLASSES_PATH = "Software\\Classes\\"; try { if (!Advapi32Util.registryKeyExists(REG_CLASSES_HKEY,REG_CLASSES_PATH + ".swf")) { return false; } String clsName = Advapi32Util.registryGetStringValue(REG_CLASSES_HKEY,REG_CLASSES_PATH + ".swf",""); if (clsName == null) { return false; } return Advapi32Util.registryKeyExists(REG_CLASSES_HKEY,REG_CLASSES_PATH + clsName + "\\shell\\ffdec"); } catch (Win32Exception ex) { return false; } }
public static String getbrowserExePath(String browserName) { String value = null; try { value = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE,WIN_REG_CLIENTS_PATH + "\\" + browserName + "\\shell\\open\\command",""); } catch (Win32Exception e) { return null; } return value; }
/** * 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,(byte)alpha,User32.LWA_ALPHA)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } }
private File loadOsuInstallationDirectory() { if (!System.getProperty("os.name").startsWith("Win")) { return null; } final WinReg.HKEY rootKey = WinReg.HKEY_CLASSES_ROOT; final String regKey = "osu\\DefaultIcon"; final String regValue = null; // default value final String regPathPattern = "\"(.+)\\\\[^\\/]+\\.exe\""; String value; try { value = Advapi32Util.registryGetStringValue(rootKey,regValue); } catch (Win32Exception ignored) { return null; } Pattern pattern = Pattern.compile(regPathPattern); Matcher m = pattern.matcher(value); if (!m.find()) { return null; } File dir = new File(m.group(1)); if (dir.isDirectory()) { return dir; } return null; }
@CheckForNull private IWindowsAccount getwindowsAccount(String userName) { IWindowsAccount windowsAccount = null; try { windowsAccount = windowsAuthProvider.lookupAccount(userName); } catch (Win32Exception win32Exception) { LOG.debug("User {} is not found: {}",win32Exception.getMessage()); } return windowsAccount; }
@Test public void getUserDetailsFromUserNameWindowsAccountNulltest() { String userName = "User"; String domainName = "Domain"; String userNameWithDomain = getAccountNameWithDomain(domainName,"\\",userName); Win32Exception win32Exception = mock(Win32Exception.class); IWindowsAccount windowsAccount = getIWindowsAccount(domainName,userName); assertthat(authenticationHelper.getUserDetails(userNameWithDomain)).isNull(); Mockito.when(windowsAuthProvider.lookupAccount(userNameWithDomain)).thenThrow(win32Exception); assertthat(authenticationHelper.getUserDetails(userNameWithDomain)).isNull(); Mockito.verify(win32Exception,Mockito.times(1)).getMessage(); }
protected boolean isKerioInstalled() { try { String key = "SOFTWARE\\Kerio"; if (!Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE,key)) { key = "SOFTWARE\\Wow6432Node\\Kerio"; return Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE,key); } return true; } catch (Win32Exception e) { LOGGER.debug("Could not get Kerio information from Windows registry: {}",e); return false; } }
@Override public MemoryBuffer read(Pointer address,int size,MemoryBuffer buffer) { if (Kernel32.ReadProcessMemory(pointer(),address,buffer,size,0) == 0) { throw new Win32Exception(Native.getLastError()); } return buffer; }
@Override public Process write(Pointer address,MemoryBuffer buffer) { if (Kernel32.WriteProcessMemory(pointer(),buffer.size(),0) == 0) { throw new Win32Exception(Native.getLastError()); } return this; }
/** * Gets a list of currently active processes by creating a snapshot. * * @return List of currently active processes * @throws Win32Exception * If the operation was not successful */ public static ProcessList getProcessList() throws Win32Exception { final ProcessList plist = new ProcessList(); final List<PROCESSENTRY32> list = new LinkedList<>(); final HANDLE hProcessSnap = Kernel32.INSTANCE.Createtoolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS,new DWORD(0)); PROCESSENTRY32 pe32 = new PROCESSENTRY32(); if (!Kernel32.INSTANCE.Process32First(hProcessSnap,pe32)) { throw new Win32Exception(Native.getLastError()); } do { if (pe32.th32ProcessID.intValue() != 0) { list.add(pe32); } pe32 = new PROCESSENTRY32(); } while (Kernel32.INSTANCE.Process32Next(hProcessSnap,pe32)); for (final PROCESSENTRY32 pe : list) { plist.add(new Process(pe)); } Kernel32.INSTANCE.CloseHandle(hProcessSnap); final List<DesktopWindow> windows = WindowUtils.getAllWindows(false); final IntByReference lpdwProcessId = new IntByReference(); int pid = 0; for (final DesktopWindow window : windows) { User32.INSTANCE.GetwindowThreadProcessId(window.getHWND(),lpdwProcessId); pid = lpdwProcessId.getValue(); plist.add(pid,window.getHWND()); } return plist; }
/** * Whether the given process is a 64-bit application or not. A 32-bit * application that runs in the WoW64 environment is not considered as * 64-bit application,since they are restricted to the 32-bit memory space. * * @param hProcess * Handle to the process in question * @return <tt>True</tt> if the given process is a 64-bit application,* <tt>false</tt> otherwise. * @throws Win32Exception * If the operation was not successful */ public static boolean is64Bit(final HANDLE hProcess) throws Win32Exception { if (System.getenv(SystemProperties.PRC_ARCH) == Masks.PRC_ARCH_32BIT) { return false; } final IntByReference isWow64 = new IntByReference(); final boolean success = Kernel32.INSTANCE.IsWow64Process(hProcess,isWow64); if (!success) { throw new Win32Exception(Native.getLastError()); } return isWow64.getValue() == 0; }
public static String getAppVersionValue() throws RegistryCanNotReadInfoException { if (SETTINGS.getProperty(KEY_CURRENT_VERSION) == null || SETTINGS.getProperty(KEY_CURRENT_VERSION).isEmpty()) { try { String result = Advapi32Util.registryGetStringValue(APP_ROOT_HKEY,KEY_CURRENT_VERSION); SETTINGS.setProperty(KEY_CURRENT_VERSION,result); return result; } catch (Win32Exception e) { throw new RegistryCanNotReadInfoException("Can not get app version value",e); } } else return SETTINGS.getProperty(KEY_CURRENT_VERSION); }
public static boolean isAutoUpdateActive() throws RegistryCanNotReadInfoException { if (SETTINGS.getProperty(KEY_AUTO_UPDATE) == null || SETTINGS.getProperty(KEY_AUTO_UPDATE).isEmpty()) { try { String value = Advapi32Util.registryGetStringValue(APP_ROOT_HKEY,KEY_AUTO_UPDATE); boolean result = Boolean.parseBoolean(value); //prevents SETTINGS.setProperty(KEY_AUTO_UPDATE,Boolean.toString(result)); return result; } catch (Win32Exception e) { throw new RegistryCanNotReadInfoException("Can not read " + RegistryManager.KEY_AUTO_UPDATE + " value",e); } } else return Boolean.parseBoolean(SETTINGS.getProperty(KEY_AUTO_UPDATE)); }
public static void createRegistryEntry(String path,String valueName,String value) throws RegistryCanNotWriteInfoException { try { SETTINGS.setProperty(valueName,value); Advapi32Util.registrySetStringValue(APP_ROOT_HKEY,path,valueName,value); } catch (Win32Exception e) { throw new RegistryCanNotWriteInfoException("Can not create entry at: " + APP_ROOT_HKEY + "\\" + path + valueName + " With value [" + value + "]",e); } }
public static void createRootRegistryFolder(String path) throws RegistryCanNotWriteInfoException { if (!Advapi32Util.registryKeyExists(APP_ROOT_HKEY,path)) { try { Advapi32Util.registryCreateKey(APP_ROOT_HKEY,path); } catch (Win32Exception e) { throw new RegistryCanNotWriteInfoException("Can not create root folder on registry.",e); } } }
String getToken( final CtxtHandle continueCtx,final SecBufferDesc continuetoken,final String targetName) { final IntByReference attr = new IntByReference(); final SecBufferDesc token = new SecBufferDesc( sspi.SECBUFFER_TOKEN,sspi.MAX_TOKEN_SIZE); sspiContext = new CtxtHandle(); final int rc = Secur32.INSTANCE.InitializeSecurityContext(clientCred,continueCtx,targetName,sspi.ISC_REQ_DELEGATE | sspi.ISC_REQ_MUTUAL_AUTH,sspi.Security_NATIVE_DREP,continuetoken,sspiContext,token,attr,null); switch (rc) { case WinError.SEC_I_CONTINUE_NEEDED: continueNeeded = true; break; case WinError.SEC_E_OK: dispose(); // Don't keep the context continueNeeded = false; break; default: dispose(); throw new Win32Exception(rc); } return Base64.encodeBase64String(token.getBytes()); }
@Override String getToken(final CtxtHandle continueCtx,final String targetName) { dispose(); /* We will rather throw SEC_E_TARGET_UNKNowN because SEC_E_DOWNGRADE_DETECTED is not * available on Windows XP and this unit test always fails. */ throw new Win32Exception(WinError.SEC_E_TARGET_UNKNowN); }
@Override public int getBrightness() throws Win32Exception { DWORDByReference minBrightness = new DWORDByReference(); DWORDByReference curBrightness = new DWORDByReference(); DWORDByReference maxBrightness = new DWORDByReference(); check(Dxva2.INSTANCE.GetMonitorBrightness(handle,minBrightness,curBrightness,maxBrightness)); // return curBright; return curBrightness.getValue().intValue(); }
private void check(BOOL retVal) { if (!retVal.booleanValue()) { int err = Kernel32.INSTANCE.GetLastError(); if (err != 0) throw new Win32Exception(err); } }
private CredHandle acquireCredentialsHandle() { CredHandle handle = new CredHandle(); int rc = Secur32.INSTANCE.AcquireCredentialsHandle(null,"NTLM",SECPKG_CRED_OUTBOUND,null,handle,new TimeStamp()); if (SEC_E_OK != rc) { throw new Win32Exception(rc); } return handle; }
@Test(expected = Win32Exception.class) public void test_setTransparency_Throws_Exception_When_SetwindowLong_Returns_Error() throws Exception { doAnswer(invocation -> 0).when(user32).SetwindowLong(any(),anyInt(),anyInt()); doAnswer(invocation -> true).when(user32).SetlayeredWindowAttributes(any(),anyByte(),anyInt()); doAnswer(invocation -> { Object[] args = invocation.getArguments(); Object reference = (Object)args[0]; reference = 1245; return 1234; }).when(element).getPropertyValue(anyInt()); AutomationWindow wndw = new AutomationWindow( new ElementBuilder(element).window(window).itemContainer(container).user32(user32)); wndw.setTransparency(100); verify(element,atLeastOnce()).getPropertyValue(anyInt()); }
com.sun.jna.platform.win32.WinError的实例源码
@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!"); } }
@Override public void write(byte[] b,int off,int len) throws IOException { Pointer lpOverlapped = createOverlapped(writerWaitable).getPointer(); boolean immediate = api.WriteFile(pipeHandle,ByteBuffer.wrap(b,off,len),len,lpOverlapped); if (!immediate && api.GetLastError() != WinError.ERROR_IO_PENDING) { throw new IOException("WriteFile() Failed. WinError: " + api.GetLastError()); } IntByReference written = new IntByReference(); // wait = true,blocked until data is written if (!api.GetoverlappedResult(pipeHandle,lpOverlapped,written,true)) { throw new IOException("GetoverlappedResult() Failed for write operation"); } if (written.getValue() != len) { throw new IOException("WriteFile() wrote less bytes than requested"); } }
String getToken( final CtxtHandle continueCtx,final SecBufferDesc continuetoken,final String targetName) { final IntByReference attr = new IntByReference(); final SecBufferDesc token = new SecBufferDesc( sspi.SECBUFFER_TOKEN,sspi.MAX_TOKEN_SIZE); sspiContext = new CtxtHandle(); final int rc = Secur32.INSTANCE.InitializeSecurityContext(clientCred,continueCtx,targetName,sspi.ISC_REQ_DELEGATE | sspi.ISC_REQ_MUTUAL_AUTH,sspi.Security_NATIVE_DREP,continuetoken,sspiContext,token,attr,null); switch (rc) { case WinError.SEC_I_CONTINUE_NEEDED: continueNeeded = true; break; case WinError.SEC_E_OK: dispose(); // Don't keep the context continueNeeded = false; break; default: dispose(); throw new Win32Exception(rc); } return Base64.encodeBase64String(token.getBytes()); }
@Override String getToken(final CtxtHandle continueCtx,final String targetName) { dispose(); /* We will rather throw SEC_E_TARGET_UNKNowN because SEC_E_DOWNGRADE_DETECTED is not * available on Windows XP and this unit test always fails. */ throw new Win32Exception(WinError.SEC_E_TARGET_UNKNowN); }
private static void waitForPipe(WinNT.HANDLE handle) throws IOException { WinNT.HANDLE connectEvent = KERNEL32.CreateEventA(null,true,false,null); WinBase.OVERLAPPED povl = new WinBase.OVERLAPPED(); povl.hEvent = connectEvent; boolean success = KERNEL32.ConnectNamedPipe(handle,povl); if (!success) { switch (KERNEL32.GetLastError()) { case WinError.ERROR_PIPE_CONNECTED: success = true; break; case WinError.ERROR_IO_PENDING: if (KERNEL32.WaitForSingleObject(connectEvent,CONNECT_PIPE_TIMEOUT) != WinBase.WAIT_OBJECT_0) { KERNEL32.CancelIo(handle); success = false; } else { success = true; } break; } } KERNEL32.CloseHandle(connectEvent); if (!success) throw new IOException("Cannot connect to a named pipe"); }
private static boolean isRunning() { if (Platform.isWindows()) { mutex = Kernel32.INSTANCE.CreateMutex(null,MUTEX_NAME); if (mutex == null) { return false; } int er = Kernel32.INSTANCE.GetLastError(); if (er == WinError.ERROR_ALREADY_EXISTS) { return true; } new Thread("OtherInstanceCommunicator") { @Override public void run() { while (true) { try (PipeInputStream pis = new PipeInputStream(PIPE_NAME,true)) { ObjectInputStream ois = new ObjectInputStream(pis); String app = ois.readUTF(); if (app.equals(PIPE_APP_CODE)) { int major = ois.readInt(); int minor = ois.readInt(); int release = ois.readInt(); int build = ois.readInt(); int pipeMajor = ois.readInt(); int pipeMinor = ois.readInt(); if (pipeMajor == PIPE_MAJOR) { String command = ois.readUTF(); switch (command) { case "open": int cnt = ois.readInt(); String[] fileNames = new String[cnt]; for (int i = 0; i < cnt; i++) { fileNames[i] = ois.readUTF(); } View.execInEventdispatch(() -> { for (int i = 0; i < cnt; i++) { Main.openFile(fileNames[i],null); } }); //no break - focus too case "focus": View.execInEventdispatch(new Runnable() { @Override public void run() { Window wnd = Main.getMainFrame().getwindow(); wnd.setAlwaysOnTop(true); wnd.toFront(); wnd.requestFocus(); wnd.setAlwaysOnTop(false); wnd.repaint(); } }); break; } } } } catch (IOException ex) { //ignore } } } }.start(); } return false; }
今天关于Win32 Error和win32 error 126的介绍到此结束,谢谢您的阅读,有关C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\Microsoft.Cpp.Win32 .Targets(147,5): error MSB6006:、com.sun.jna.platform.win32.W32Errors的实例源码、com.sun.jna.platform.win32.Win32Exception的实例源码、com.sun.jna.platform.win32.WinError的实例源码等更多相关知识的信息可以在本站进行查询。
本文标签: