상속: ExternalException, ISerializable
        public DebugHelper(string exeName)
        {
            IntPtr handle = Process.GetCurrentProcess().Handle;
            NativeMethods.SetErrorMode(NativeMethods.SetErrorFlags.SEM_FAILCRITICALERRORS | NativeMethods.SetErrorFlags.SEM_NOOPENFILEERRORBOX);

            NativeMethods.SymSetOptions(NativeMethods.Options.SYMOPT_DEFERRED_LOADS | NativeMethods.Options.SYMOPT_DEBUG);

            if (!NativeMethods.SymInitialize(handle, null, false))
            {
                var ex = new Win32Exception(Marshal.GetLastWin32Error());
                LastErrorMessage = ex.Message;
            }

            _dllBase = NativeMethods.SymLoadModuleEx(handle,
                IntPtr.Zero,
                exeName,
                null,
                0,
                0,
                IntPtr.Zero,
                NativeMethods.SymLoadModuleFlags.SLMFLAG_NONE);
            if (_dllBase == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            _libHandle = handle;
        }
예제 #2
0
파일: InProcessHost.cs 프로젝트: ifzz/FDK
        static void ThrowCanNotLoadDll(string dllPath, int error)
        {
            var type = WinAPI.GetDllMachineType(dllPath);
            if (type == MachineType.IMAGE_FILE_MACHINE_I386)
            {
                if (sizeof(long) == IntPtr.Size)
                {
                    var message = string.Format("x64 process tries to load x86 dll = {0}; code = 0x{1:X}", dllPath, error);
                    throw new Exception(message);
                }
            }
            else if (type == MachineType.IMAGE_FILE_MACHINE_AMD64)
            {
                if (sizeof(int) == IntPtr.Size)
                {
                    var message = string.Format("x86 process tries to load x64 dll = {0}; code = 0x{1:X}", dllPath, error);
                    throw new Exception(message);
                }
            }
            else
            {
                var message = string.Format("Unsupported machine type = {0} of dll = {1}; error = 0x{2:X}.", type, dllPath, error);
                throw new Exception(message);
            }

            {
                var ex = new Win32Exception(error);
                var message = string.Format("Can not load library = {0} Code={1}", dllPath, error);
                throw new Exception(message, ex);
            }
        }
예제 #3
0
    static void Main(string[] args)
    {
        var ex = new System.ComponentModel.Win32Exception(unchecked ((int)0x80004005));

        Console.WriteLine(ex.Message);
        Console.ReadLine();
    }
예제 #4
0
            public DVDBuilderException(int error, int errorFacility, string hint)
            {
                m_error         = error;
                m_errorFacility = errorFacility;
                m_hint          = hint;

                switch (m_errorFacility)
                {
                case (int)PrimoSoftware.DVDBuilder.ErrorFacility.Success:
                    m_message = "Success.";
                    return;

                case (int)PrimoSoftware.DVDBuilder.ErrorFacility.SystemWindows:
                    System.ComponentModel.Win32Exception sysex = new System.ComponentModel.Win32Exception(m_error);
                    m_message = "System error: " + sysex.Message;
                    return;

                case (int)PrimoSoftware.DVDBuilder.ErrorFacility.DVDBuilder:
                    m_message = "DVDBuilderError: " + ((PrimoSoftware.DVDBuilder.DVDBuilderError)m_error).ToString();
                    return;

                default:
                    m_message = "Unknown error.";
                    return;
                }
            }
예제 #5
0
        public static void InstantiateException()
        {
            int error = 5;
            string message = "This is an error message.";
            Exception innerException = new FormatException();

            // Test each of the constructors and validate the properties of the resulting instance

            Win32Exception ex = new Win32Exception();
            Assert.Equal(expected: E_FAIL, actual: ex.HResult);

            ex = new Win32Exception(error);
            Assert.Equal(expected: E_FAIL, actual: ex.HResult);
            Assert.Equal(expected: error, actual: ex.NativeErrorCode);

            ex = new Win32Exception(message);
            Assert.Equal(expected: E_FAIL, actual: ex.HResult);
            Assert.Equal(expected: message, actual: ex.Message);

            ex = new Win32Exception(error, message);
            Assert.Equal(expected: E_FAIL, actual: ex.HResult);
            Assert.Equal(expected: error, actual: ex.NativeErrorCode);
            Assert.Equal(expected: message, actual: ex.Message);

            ex = new Win32Exception(message, innerException);
            Assert.Equal(expected: E_FAIL, actual: ex.HResult);
            Assert.Equal(expected: message, actual: ex.Message);
            Assert.Same(expected: innerException, actual: ex.InnerException);
        }
예제 #6
0
파일: Owner.cs 프로젝트: galaxy001/WindSLIC
        public static void ChangeOwner(String s_Path, String s_UserName)
        {
            IntPtr pNewOwner, peUse;
            Win32Exception Win32Error;
            String domain_name;
            int ret, sid_len, domain_len;

            if (Privileges.SetPrivileges() == false)
                throw new Exception("Required privilege not held by the user");

            sid_len = SID_SIZE;
            pNewOwner = Marshal.AllocHGlobal(sid_len);
            domain_len = NAME_SIZE;
            domain_name = String.Empty.PadLeft(domain_len);
            peUse = IntPtr.Zero;

            if (!Imports.LookupAccountName(null, s_UserName, pNewOwner, ref sid_len, domain_name, ref domain_len, ref peUse))
            {
                ret = Marshal.GetLastWin32Error();
                Win32Error = new Win32Exception(ret);
                throw new Exception(Win32Error.Message);
            }
            ret = Imports.SetNamedSecurityInfo(s_Path, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, pNewOwner, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            if (ret != 0)
            {
                Win32Error = new Win32Exception(ret);
                throw new Exception(Win32Error.Message);
            }
            Marshal.FreeHGlobal(pNewOwner);
        }
예제 #7
0
 protected void InstallHook(HookType hookType)
 {
     lock (HookLock)
     {
         // If hook is installed already then return.
         _hookType = hookType;
         if (hHook.Handle != IntPtr.Zero)
         {
             return;
         }
         string lpModuleName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
         var    hMod         = GetModuleHandle(lpModuleName);
         //var hRef = new HandleRef(this, hMod);
         HookProcedure = new HookProc(HookProcess);
         IntPtr kh;
         if (hookType == HookType.WH_MOUSE)
         {
             uint threadId = GetCurrentThreadId();
             kh = SetWindowsHookEx((uint)hookType, HookProcedure, hMod, threadId);
         }
         else
         {
             kh = SetWindowsHookEx((uint)hookType, HookProcedure, hMod, 0);
         }
         if (kh == IntPtr.Zero)
         {
             var ex = new System.ComponentModel.Win32Exception();
             throw new Exception(ex.Message);
         }
         hHook = new HandleRef(null, kh);
     }
 }
예제 #8
0
        public static Bitmap GetDesktopWindowCaptureAsBitmap()
        {
            Rectangle rcScreen = Rectangle.Empty;

            Screen[] screens = Screen.AllScreens;

            // Create a rectangle encompassing all screens...
            foreach (Screen screen in screens)
            {
                rcScreen = Rectangle.Union(rcScreen, screen.Bounds);
            }
            //			System.Diagnostics.Trace.WriteLine(rcScreen);

            // Create a composite bitmap of the size of all screens...
            Bitmap finalBitmap = new Bitmap(rcScreen.Width, rcScreen.Height);

            // Get a graphics object for the composite bitmap and initialize it...
            Graphics g = Graphics.FromImage(finalBitmap);

            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
            g.FillRectangle(SystemBrushes.Desktop, 0, 0, rcScreen.Width - rcScreen.X, rcScreen.Height - rcScreen.Y);

            // Get an HDC for the composite area...
            IntPtr hdcDestination = g.GetHdc();

            // Now, loop through screens, BitBlting each to the composite HDC created above...
            foreach (Screen screen in screens)
            {
                // Create DC for each source monitor...
                IntPtr hdcSource = Win32.CreateDC(IntPtr.Zero, screen.DeviceName, IntPtr.Zero, IntPtr.Zero);

                // Blt the source directly to the composite destination...
                int xDest = screen.Bounds.X - rcScreen.X;
                int yDest = screen.Bounds.Y - rcScreen.Y;
                //				bool success = BitBlt(hdcDestination, xDest, yDest, screen.Bounds.Width, screen.Bounds.Height, hdcSource, 0, 0, (int)TernaryRasterOperations.SRCCOPY);
                bool success = Win32.StretchBlt(hdcDestination, xDest, yDest, screen.Bounds.Width, screen.Bounds.Height, hdcSource, 0, 0, screen.Bounds.Width, screen.Bounds.Height, (int)Win32.TernaryRasterOperations.SRCCOPY);
                //				System.Diagnostics.Trace.WriteLine(screen.Bounds);
                if (!success)
                {
                    System.ComponentModel.Win32Exception win32Exception = new System.ComponentModel.Win32Exception();
                    System.Diagnostics.Trace.WriteLine(win32Exception);
                }

                // Cleanup source HDC...
                Win32.DeleteDC(hdcSource);
            }

            // Cleanup destination HDC and Graphics...
            g.ReleaseHdc(hdcDestination);
            g.Dispose();

            //			IntPtr hDC = GetDC(IntPtr.Zero);
            //			Graphics gDest = Graphics.FromHdc(hDC);
            //			gDest.DrawImage(finalBitmap, 0, 0, 640, 480);
            //			gDest.Dispose();
            //			ReleaseDC(IntPtr.Zero, hDC);

            // Return composite bitmap which will become our Form's PictureBox's image...
            return(finalBitmap);
        }
예제 #9
0
		[Test] // ctor (int)
		public void Constructor1 ()
		{
			Win32Exception ex;

			ex = new Win32Exception (0);
			Assert.AreEqual (-2147467259, ex.ErrorCode, "#A1");
			Assert.IsNull (ex.InnerException, "#A2");
			Assert.IsNotNull (ex.Message, "#A3");
			Assert.IsFalse (ex.Message.IndexOf (ex.GetType ().FullName) != -1, "#A4");
			Assert.AreEqual (0, ex.NativeErrorCode, "#A5");

			ex = new Win32Exception (int.MinValue);
			Assert.AreEqual (-2147467259, ex.ErrorCode, "#B1");
			Assert.IsNull (ex.InnerException, "#B2");
			Assert.IsNotNull (ex.Message, "#B3");
			Assert.IsFalse (ex.Message.IndexOf (ex.GetType ().FullName) != -1, "#B4");
			Assert.AreEqual (int.MinValue, ex.NativeErrorCode, "#B5");

			ex = new Win32Exception (int.MaxValue);
			Assert.AreEqual (-2147467259, ex.ErrorCode, "#C1");
			Assert.IsNull (ex.InnerException, "#C2");
			Assert.IsNotNull (ex.Message, "#C3");
			Assert.IsFalse (ex.Message.IndexOf (ex.GetType ().FullName) != -1, "#C4");
			Assert.AreEqual (int.MaxValue, ex.NativeErrorCode, "#C5");
		}
예제 #10
0
파일: ECLinux.cs 프로젝트: binmallow/nbfc
        public bool AquireLock(int timeout)
        {
            bool success = false;

            if (Monitor.TryEnter(syncRoot, timeout))
            {
                if (this.stream == null)
                {
                    int fd = Syscall.open(PortFilePath, OpenFlags.O_RDWR | OpenFlags.O_EXCL);

                    if (fd == -1)
                    {
                        var e = new Win32Exception(Marshal.GetLastWin32Error());
                        Debug.WriteLine(string.Format("Error opening {0}: {1}", PortFilePath, e.Message));

                        Monitor.Exit(syncRoot);
                    }
                    else
                    {
                        this.stream = new UnixStream(fd);
                        success = true;
                    }
                }
            }

            return success;
        }
예제 #11
0
        public static Bitmap CaptureWindow(IntPtr handle, int x, int y, int width, int height)
        {
            // Get the size of the window to capture
            Rectangle rect = new Rectangle();

            Win32.GetWindowRect(handle, ref rect);

            // GetWindowRect returns Top/Left and Bottom/Right, so fix it
            rect.Width  = rect.Width - rect.X;
            rect.Height = rect.Height - rect.Y;

            // Create a bitmap to draw the capture into
            Bitmap bitmap = new Bitmap(rect.Width, rect.Height);

            // Use PrintWindow to draw the window into our bitmap
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                IntPtr hdc = g.GetHdc();
                if (!Win32.PrintWindow(handle, hdc, 0))
                {
                    int error     = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(error);
                    Debug.WriteLine("ERROR: " + error + ": " + exception.Message);
                    // TODO: Throw the exception?
                }
                g.ReleaseHdc(hdc);
            }

            x += px;
            y += py;
            return(bitmap);
            //return bitmap.Clone(new Rectangle(x, y, width, height), bitmap.PixelFormat);
        }
		// --------------------------------------------------------------------------- ------------- 
		// Class Name:  VolumeFunctions 
		// Procedure Name: UnmapFolderFromDrive 
		// Purpose:   Unmap a drive letter. We always unmp the drive, without checking the 
		//                  folder name. 
		// Parameters: 
		//  - driveLetter (string)  :   Drive letter to be released, the the format "C:" 
		//  - folderName (string)  :    Folder name that the drive is mapped to. 
		// --------------------------------------------------------------------------- ------------- 
		internal static string UnmapFolderFromDrive(string driveLetter, string folderName)
		{
			DefineDosDevice(DDD_REMOVE_DEFINITION, driveLetter, folderName);
			// Display the status of the "last" unmap we run. 
			string statusMessage = new Win32Exception(Marshal.GetLastWin32Error()).ToString();
			return statusMessage.Substring(statusMessage.IndexOf(":") + 1);
		}
예제 #13
0
    public static Bitmap PrintWindow(IntPtr handle)
    {
        Rectangle rect = new Rectangle();

        GetWindowRect(handle, ref rect);

        rect.Width  = rect.Width - rect.X;
        rect.Height = rect.Height - rect.Y;

        using (Bitmap bitmap = new Bitmap(rect.Width, rect.Height))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                IntPtr hdc = g.GetHdc();
                if (!PrintWindow(handle, hdc, 0))
                {
                    int error     = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(error);
                    Debug.WriteLine("ERROR: " + error + ": " + exception.Message);
                }
                g.ReleaseHdc(hdc);
                bitmap.Save("./asdf.png");
                Bitmap Clone = (Bitmap)bitmap.Clone();
                return(Clone);
            }
        }
    }
예제 #14
0
 /// <summary>
 /// Handles any errors that CreateDirectoryEx may encounter
 /// </summary>
 private static void HandleCreateDirectoryExError(string template, string target, int errorCode)
 {
     Win32Exception win32Exception = new Win32Exception(errorCode);
     Exception error;
     switch ((Win32Error)errorCode)
     {
         case Win32Error.ACCESS_DENIED:
             error = new UnauthorizedAccessException(
                 string.Format("Access was denied to clone '{0}' to '{1}'.", template, target),
                 win32Exception);
             break;
         case Win32Error.PATH_NOT_FOUND:
             error = new DirectoryNotFoundException(
                 string.Format("The path '{0}' or '{1}' could not be found.", template, target),
                 win32Exception);
             break;
         case Win32Error.SHARING_VIOLATION:
             error = new SharingViolationException(
                 string.Format("The source or destination file was in use when copying '{0}' to '{1}'.", template, target),
                 win32Exception);
             break;
         case Win32Error.ALREADY_EXISTS:
             //If the directory already exists don't worry about it.
             return;
         default:
             error = win32Exception;
             break;
     }
     throw error;
 }
		// WinUser.h


		/// <summary>Returns an exception corresponding to the last Win32 error.</summary>
		/// <returns>Returns an exception corresponding to the last Win32 error.</returns>
		internal static Exception GetExceptionForLastWin32Error()
		{
			var errorCode = Marshal.GetLastWin32Error();
			var ex = Marshal.GetExceptionForHR( errorCode );
			if( ex == null )
				ex = new Win32Exception( errorCode );
			return ex;
		}
 public ExternalToolLaunchException(string ExecutableFilePath, string WorkingDirectoryPath, IEnumerable<ILaunchParameter> Parameters,
                                    Win32Exception inner)
     : base(string.Format("{0} ({1})", ExceptionMessage, ExecutableFilePath.Split(Path.DirectorySeparatorChar).Last()), inner)
 {
     this.ExecutableFilePath = ExecutableFilePath;
     this.WorkingDirectoryPath = WorkingDirectoryPath;
     this.Parameters = Parameters;
 }
예제 #17
0
 public void WriteValue(string strSection, string strKey, string strValue)
 {
     int res = WritePrivateProfileString(strSection, strKey, strValue, this.m_fileName);
     if (res == 0)
     {
         Win32Exception wexp = new Win32Exception(Marshal.GetLastWin32Error());
         throw new IniFileParsingException("win32:" + wexp.Message);
     }
 }
예제 #18
0
 /// <summary>
 /// Closes the console associate to the current process
 /// </summary>
 public static void CloseConsole()
 {
     bool result = FreeConsole();
     if (!result)
     {
         Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
         throw new Exception(string.Format("Failed to close console: {0}", ex.Message));
     }
 }
예제 #19
0
        protected override void OnStartup(StartupEventArgs e)
        {
            var test = Shcore.SetProcessDpiAwareness(PROCESS_DPI_AWARENESS.PROCESS_PER_MONITOR_DPI_AWARE);
            if (!test)
            {
                var err = new Win32Exception();
            }

            base.OnStartup(e);
        }
예제 #20
0
파일: Network.cs 프로젝트: bholl/zeroc-ice
 public static bool acceptInterrupted(Win32Exception ex)
 {
     if(interrupted(ex))
     {
         return true;
     }
     int error = ex.NativeErrorCode;
     return error == WSAECONNABORTED ||
            error == WSAECONNRESET ||
            error == WSAETIMEDOUT;
 }
예제 #21
0
	public void OpenForReading(string FileName)
	{
		Close();
		pHandle = CreateFile( FileName, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0 );
		if (pHandle == System.IntPtr.Zero)
		{
			Win32Exception WE = new Win32Exception();
			ApplicationException AE = new ApplicationException("WinFileIO:OpenForReading - Could not open file " + FileName + " - " + WE.Message);
			throw AE;
		}
	}
예제 #22
0
		[Test] // ctor ()
		public void Constructor0 ()
		{
			int native_error = Marshal.GetLastWin32Error ();

			Win32Exception ex = new Win32Exception ();
			Assert.AreEqual (-2147467259, ex.ErrorCode, "#1");
			Assert.IsNull (ex.InnerException, "#2");
			Assert.IsNotNull (ex.Message, "#3");
			Assert.IsFalse (ex.Message.IndexOf (ex.GetType ().FullName) != -1, "#4");
			Assert.AreEqual (native_error, ex.NativeErrorCode, "#5");
		}
예제 #23
0
 /// <summary>
 /// managed wrapper around LoadLibrary
 /// </summary>
 /// <param name="dllName"></param>
 internal static void LoadDll(string dllName)
 {
     if (tempFolder == "")
     throw new Exception("Please call ExtractEmbeddedDlls before LoadDll");
       IntPtr h = LoadLibrary(dllName);
       if (h == IntPtr.Zero)
       {
     Exception e = new Win32Exception();
     throw new DllNotFoundException(String.Format("Unable to load library: {0} from {1}", dllName, tempFolder), e);
       }
 }
예제 #24
0
	public int Read(int BytesToRead)
	{
		int BytesRead = 0;
		if (!ReadFile( pHandle, pBuffer, BytesToRead, &BytesRead, 0 ))
		{
			Win32Exception WE = new Win32Exception();
			ApplicationException AE = new ApplicationException( "WinFileIO:Read - Error occurred reading a file. - " + WE.Message);
			throw AE;
		}
		return BytesRead;
	}
예제 #25
0
        static SafeCloseHandle OpenProcessForQuery(int pid)
        {
#pragma warning suppress 56523 // Microsoft, Win32Exception ctor calls Marshal.GetLastWin32Error()
            SafeCloseHandle process = ListenerUnsafeNativeMethods.OpenProcess(ListenerUnsafeNativeMethods.PROCESS_QUERY_INFORMATION, false, pid);
            if (process.IsInvalid)
            {
                Exception exception = new Win32Exception();
                process.SetHandleAsInvalid();
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception);
            }
            return process;
        }
예제 #26
0
 public void ShouldSetInnerException()
 {
     var result = Result.RzSuccess;
     var expected = new Win32Exception(result);
     var actual = new NativeCallException("TestFunc", result).InnerException;
     Assert.AreEqual(expected.GetType(), actual.GetType(), "Expected types to be equal.");
     Assert.AreEqual(expected.HResult, actual.HResult, "Expected HResults to be equal.");
     Assert.AreEqual(expected.Message, actual.Message, "Expected message to be equal.");
     Assert.AreEqual(
         expected.NativeErrorCode,
         ((Win32Exception)actual).NativeErrorCode,
         "Expected native error codes to be equal.");
 }
예제 #27
0
        static SafeCloseHandle OpenCurrentProcessForWrite()
        {
            int processId = Process.GetCurrentProcess().Id;
#pragma warning suppress 56523 // Microsoft, Win32Exception ctor calls Marshal.GetLastWin32Error()
            SafeCloseHandle process = ListenerUnsafeNativeMethods.OpenProcess(ListenerUnsafeNativeMethods.PROCESS_QUERY_INFORMATION | ListenerUnsafeNativeMethods.WRITE_DAC | ListenerUnsafeNativeMethods.READ_CONTROL, false, processId);
            if (process.IsInvalid)
            {
                Exception exception = new Win32Exception();
                process.SetHandleAsInvalid();
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception);
            }
            return process;
        }
예제 #28
0
      private static string Reporter(bool condensed = false)
      {
         var lastError = new Win32Exception();

         StopWatcher();

         if (condensed)
            return string.Format(CultureInfo.CurrentCulture, "{0} [{1}: {2}]", StopWatcher(), lastError.NativeErrorCode,
                                 lastError.Message);

         return string.Format(CultureInfo.CurrentCulture, "\t\t{0}\t*Win32 Result: [{1, 4}]\t*Win32 Message: [{2}]",
                              StopWatcher(), lastError.NativeErrorCode, lastError.Message);
      }
		// --------------------------------------------------------------------------- ------------- 
		// Class Name:  VolumeFunctions 
		// Procedure Name: MapFolderToDrive 
		// Purpose:   Map the folder to a drive letter 
		// Parameters: 
		//  - driveLetter (string)  : Drive letter in the format "C:" without a back slash 
		//  - folderName (string)  : Folder to map without a back slash 
		// --------------------------------------------------------------------------- ------------- 
		internal static string MapFolderToDrive(string driveLetter, string folderName)
		{
			// Is this drive already mapped? If so, we don't remap it! 
			StringBuilder volumeMap = new StringBuilder(1024);
			QueryDosDevice(driveLetter, volumeMap, (uint)1024);
			if (volumeMap.ToString().StartsWith(MAPPED_FOLDER_INDICATOR) == true)
				return "Volume is already mapped - map not changed";
			// Map the folder to the drive 
			DefineDosDevice(0, driveLetter, folderName);
			// Display a status message to the user. 
			string statusMessage = new Win32Exception(Marshal.GetLastWin32Error()).ToString();
			return statusMessage.Substring(statusMessage.IndexOf(":") + 1);
		}
예제 #30
0
        public static Stream waitForFileAccess(string filePath, FileAccess access, int timeoutMs,
                                               CancellationToken token)
        {
            IntPtr   fHandle;
            int      errorCode;
            DateTime start = DateTime.Now;

            uint desiredAccess = (uint)CreateFileAccess.GENERIC_READ;
            int  fileShare     = (int)CreateFileShare.FILE_SHARE_READ;

            if (access == FileAccess.Write || access == FileAccess.ReadWrite)
            {
                desiredAccess |= (int)CreateFileAccess.GENERIC_WRITE;
                fileShare      = (int)CreateFileShare.NONE;
            }

            int creationDisposition = (int)CreateFileCreationDisposition.OPEN_EXISTING;
            int fileAttributes      = (int)(CreateFileAttributes.NORMAL | CreateFileAttributes.FILE_FLAG_RANDOM_ACCESS);

            while (true)
            {
                fHandle = CreateFileW(filePath, desiredAccess, fileShare, IntPtr.Zero,
                                      creationDisposition, fileAttributes, IntPtr.Zero);

                errorCode = Marshal.GetLastWin32Error();

                if (fHandle != IntPtr.Zero && fHandle.ToInt64() != -1L)
                {
                    Microsoft.Win32.SafeHandles.SafeFileHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(fHandle, true);

                    return(new FileStream(handle, access));
                }

                if (errorCode != ERROR_SHARING_VIOLATION)
                {
                    Win32Exception e = new System.ComponentModel.Win32Exception(errorCode);

                    throw new IOException(e.Message, errorCode);
                }
                else if (timeoutMs >= 0 && (DateTime.Now - start).TotalMilliseconds > timeoutMs)
                {
                    throw new TimeoutException("Timed out waiting for file access: " + filePath);
                }
                else if (token != null && token.IsCancellationRequested == true)
                {
                    return(null);
                }

                Thread.Sleep(100);
            }
        }
예제 #31
0
        static void Main(string[] args)
        {
            bool result = false;
            Mutex mutex = new Mutex(true, "vibranceGUI~Mutex", out result);
            if (!result)
            {
                MessageBox.Show("You can run vibranceGUI only once at a time!", messageBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            GraphicsAdapter adapter = GraphicsAdapterHelper.getAdapter();
            Form vibranceGUI = null;

            if (adapter == GraphicsAdapter.AMD)
            {
                vibranceGUI = new AmdVibranceGUI();
            }
            else if (adapter == GraphicsAdapter.NVIDIA)
            {
                vibranceGUI = new NvidiaVibranceGUI();
            }
            else if (adapter == GraphicsAdapter.UNKNOWN)
            {
                string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
                if (MessageBox.Show(errorGraphicsAdapterUnknown + errorMessage,
                    messageBoxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start("https://twitter.com/juvlarN");
                }
                return;
            }
            if (args.Contains("-minimized"))
            {
                vibranceGUI.WindowState = FormWindowState.Minimized;
                vibranceGUI.ShowInTaskbar = false;
                if (vibranceGUI is AmdVibranceGUI)
                {
                    ((AmdVibranceGUI) vibranceGUI).SetAllowVisible(false);
                }
                else
                {
                    ((NvidiaVibranceGUI) vibranceGUI).SetAllowVisible(false);
                }
            }
            Application.Run(vibranceGUI);

            GC.KeepAlive(mutex);
        }
예제 #32
0
 public static void CheckWNetError(int errorCode)
 {
     if (errorCode == 0x4b8)
     {
         int num;
         StringBuilder lpErrorBuf = new StringBuilder(0x400);
         StringBuilder lpNameBuf = new StringBuilder(0x400);
         Winnetwk.WNetGetLastError(out num, lpErrorBuf, lpErrorBuf.Capacity, lpNameBuf, lpNameBuf.Capacity);
         throw new NetworkException(lpErrorBuf.ToString(), num, lpNameBuf.ToString());
     }
     if (errorCode != 0)
     {
         Exception innerException = new Win32Exception(errorCode);
         throw new IOException(innerException.Message, innerException);
     }
 }
예제 #33
0
        /// <summary>
        /// Builds a suitable <see cref="Exception"/> for a given <see cref="Win32Exception.NativeErrorCode"/>.
        /// </summary>
        private Exception BuildException(int error)
        {
            switch (error)
            {
                case Win32ErrorFailNoactionReboot:
                case Win32ErrorFailShutdown:
                case Win32ErrorFailRestart:
                    bool permissionDenied;
                    string message = new Win32Exception(error).Message + Environment.NewLine + StringUtils.Join(Environment.NewLine, ListAppProblems(out permissionDenied));

                    if (permissionDenied) return new UnauthorizedAccessException(message);
                    else return new IOException(message);

                default:
                    return WindowsUtils.BuildException(error);
            }
        }
예제 #34
0
 public List<string> GetCategories()
 {
     string returnString = new string(' ', MAXCATEGORIESLENGTH);
     int res = GetPrivateProfileString(null, null, null, returnString, MAXCATEGORIESLENGTH, this.m_fileName);
     if (res == 0)
     {
         Win32Exception wexp = new Win32Exception(Marshal.GetLastWin32Error());
         throw new IniFileParsingException("win32:no categories. " + wexp.Message);
     }
     if (res == MAXCATEGORIESLENGTH - 2) //see docs: means buffer is full
     {
         throw new IniFileParsingException("data in categories is too long. must be <" + MAXCATEGORIESLENGTH);
     }
     List<string> result = new List<string>(returnString.Split('\0'));
     result.RemoveRange(result.Count - 2, 2); //removes the last 2 entries.
     return result;
 }
 internal static Win32Exception CreateSafeWin32Exception(int error)
 {
     Win32Exception exception = null;
     new SecurityPermission(PermissionState.Unrestricted).Assert();
     try
     {
         if (error == 0)
         {
             return new Win32Exception();
         }
         exception = new Win32Exception(error);
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
     return exception;
 }
예제 #36
0
        private static string GetWin23ExeptionMessage(System.ComponentModel.Win32Exception e)
        {
            var res = $"Exception: {e.GetType()}\n" +
                      $"Message: {e.Message}\n" +
                      $"NativeErrorCode: {e.NativeErrorCode}\n" +
                      $"ErrorCode: {e.ErrorCode}\n";

            try
            {
                res += $"Data: {string.Join("\n", e?.Data?.Keys.Cast<object>().Select(k => k.ToString() + " : " + e.Data[k].ToString()))}\n";
            }
            catch (Exception)
            { }
            res += $"\nStackTrace: " +
                   $"{e.StackTrace}";


            return(res);
        }
예제 #37
0
        internal static Win32Exception CreateSafeWin32Exception(int error) {
            Win32Exception newException = null;
            // Need to assert SecurtiyPermission, otherwise Win32Exception
            // will not be able to get the error message. At this point the right
            // permissions have already been demanded.
            SecurityPermission securityPermission = new SecurityPermission(PermissionState.Unrestricted);
            securityPermission.Assert();
            try {
                if (error == 0)
                    newException = new Win32Exception();
                else
                    newException = new Win32Exception(error);
            }
            finally {
                SecurityPermission.RevertAssert();
            }

            return newException;
        }
예제 #38
0
 private static void ThrowOnError(string path, IntPtr hModule)
 {
     if (hModule == IntPtr.Zero)
     {
         var error = Marshal.GetLastWin32Error();
         var ex    = new System.ComponentModel.Win32Exception(error);
         if (error == (int)Win32ErrorCode.ERROR_MOD_NOT_FOUND ||
             error == (int)Win32ErrorCode.ERROR_ENVVAR_NOT_FOUND)    //TODO: change exception - this happens if path not rooted
         {
             throw new System.IO.FileNotFoundException("Failed to find dll or its dependencies", path, ex);
         }
         if (error == (int)Win32ErrorCode.ERROR_BAD_EXE_FORMAT ||
             error == (int)Win32ErrorCode.ERROR_INVALID_PARAMETER)   //TODO: change exception - this happens if path not rooted
         {
             throw new BadImageFormatException("Failed to load dll", path, ex);
         }
         throw ex;
     }
 }
예제 #39
0
        public static void ChangeStartMode(ServiceController svc, ServiceStartMode mode)
        {
            //var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_CONNECT + SC_MANAGER_ENUMERATE_SERVICE);
            var scManagerHandle = OpenSCManager(null, null, ScManagerAllAccess);
            if (scManagerHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Manager Error");
            }

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                ServiceQueryConfig | ServiceChangeConfig);

            if (serviceHandle == IntPtr.Zero)
            {
                throw new ExternalException("Open Service Error");
            }

            var result = ChangeServiceConfig(
                serviceHandle,
                ServiceNoChange,
                (uint) mode,
                ServiceNoChange,
                null,
                null,
                IntPtr.Zero,
                null,
                null,
                null,
                null);

            if (result == false)
            {
                int nError = Marshal.GetLastWin32Error();
                var win32Exception = new Win32Exception(nError);
                throw new ExternalException("Could not change service start type: "
                                            + win32Exception.Message);
            }

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(scManagerHandle);
        }
예제 #40
0
    static public String CaptureWindow(IntPtr handle)
    {
        string path = System.IO.Path.GetTempPath();


        // Get the size of the window to capture
        Rectangle rect = new Rectangle();

        GetWindowRect(handle, ref rect);

        // GetWindowRect returns Top/Left and Bottom/Right, so fix it
        rect.Width  = rect.Width - rect.X;
        rect.Height = rect.Height - rect.Y;

        // Create a bitmap to draw the capture into
        using (Bitmap bitmap = new Bitmap(rect.Width, rect.Height))
        {
            // Use PrintWindow to draw the window into our bitmap
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                IntPtr hdc = g.GetHdc();
                if (!PrintWindow(handle, hdc, 0))
                {
                    int error     = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(error);
                    Debug.WriteLine("ERROR: " + error + ": " + exception.Message);
                    // TODO: Throw the exception?
                }
                g.ReleaseHdc(hdc);
                //bitmap.Save("./sa.png");
            }
            //return bitmap;
            // Save it as a .png just to demo this

            //Console.WriteLine("Capture Window path: " + ` + "a.png");
        }
        return(path + "a.png");
    }
예제 #41
0
        private unsafe byte[] GetOutgoingBlob(byte[] incomingBlob, ref Win32Exception e)
        {
            Interop.SecurityStatus statusCode;
            byte[] message = _context.GetOutgoingBlob(incomingBlob, false, out statusCode);

            if (((int)statusCode & unchecked ((int)0x80000000)) != 0)
            {
                e = new System.ComponentModel.Win32Exception((int)statusCode);

                message = new byte[8];  //sizeof(long)
                for (int i = message.Length - 1; i >= 0; --i)
                {
                    message[i] = (byte)((uint)statusCode & 0xFF);
                    statusCode = (Interop.SecurityStatus)((uint)statusCode >> 8);
                }
            }

            if (message != null && message.Length == 0)
            {
                message = s_emptyMessage;
            }

            return(message);
        }
예제 #42
0
        protected override IntPtr HookProcess(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (EnableEvents)
            {
                // If OK and someone listens to our events
                if (nCode >= 0)
                {
                    var info = new CURSORINFO();
                    info.Size = Marshal.SizeOf(info.GetType());
                    if (!GetCursorInfo(out info))
                    {
                        var ex = new System.ComponentModel.Win32Exception();
                        throw new Exception(ex.Message);
                    }
                    var button = MouseButtons.None;
                    var param  = wParam.ToInt32();
                    // Marshall the data from callback.
                    var mStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                    var delta   = 0;
                    var tu      = new TestUnion {
                        Number = mStruct.mouseData
                    };
                    MouseKey mk    = 0;
                    int      lastX = 0;
                    int      lastY = 0;
                    bool     handled;
                    switch (param)
                    {
                    case WM_MOUSEMOVE:
                        var x = mStruct.pt.x;
                        var y = mStruct.pt.y;
                        if (prevX == -1 || prevY == -1)
                        {
                            scrnX = SystemInformation.VirtualScreen.Width - 1;
                            scrnY = SystemInformation.VirtualScreen.Height - 1;
                            prevX = x;
                            prevY = y;
                        }
                        lastX = x - prevX;
                        lastY = y - prevY;
                        var fX = (int)Math.Max(Math.Min(scrnX, x), 0);
                        var fY = (int)Math.Max(Math.Min(scrnY, y), 0);
                        if (fX != x || fY != y)
                        {
                            SetCursorPos(fX, fY);
                        }
                        prevX = fX;
                        prevY = fY;
                        break;

                    case WM_LBUTTONDOWN:
                    case WM_LBUTTONUP:
                    case WM_LBUTTONDBLCLK:
                        button = MouseButtons.Left;
                        break;

                    case WM_MBUTTONDOWN:
                    case WM_MBUTTONUP:
                    case WM_MBUTTONDBLCLK:
                        button = MouseButtons.Middle;
                        break;

                    case WM_RBUTTONDOWN:
                    case WM_RBUTTONUP:
                    case WM_RBUTTONDBLCLK:
                        button = MouseButtons.Right;
                        break;

                    case WM_XBUTTONDOWN:
                    case WM_XBUTTONUP:
                    case WM_XBUTTONDBLCLK:
                        button = MouseButtons.XButton1;
                        if (tu.High == 1)
                        {
                            mk = MouseKey.MK_XBUTTON1;
                        }
                        if (tu.High == 2)
                        {
                            mk = MouseKey.MK_XBUTTON2;
                        }
                        break;

                    case WM_NCXBUTTONDOWN:
                    case WM_NCXBUTTONUP:
                    case WM_NCXBUTTONDBLCLK:
                        button = MouseButtons.XButton2;
                        if (tu.High == 1)
                        {
                            mk = MouseKey.MK_XBUTTON1;
                        }
                        if (tu.High == 2)
                        {
                            mk = MouseKey.MK_XBUTTON2;
                        }
                        break;

                    case WM_MOUSEWHEEL:
                    case WM_MOUSEHWHEEL:
                        delta = (int)tu.High;
                        mk    = (MouseKey)tu.ULow;
                        break;

                    case WM_TOUCH:
                        try
                        {
                            handled = DecodeTouch(wParam, lParam);
                        }
                        catch (Exception ex)
                        {
                            if (OnError != null)
                            {
                                OnError(this, new UnhandledExceptionEventArgs(ex, false));
                            }
                        }
                        break;
                    }
                    var ea = new MouseHookEventArgs(mStruct, info, mk, param, lastX, lastY);
                    if (OnMouseHook != null)
                    {
                        OnMouseHook(this, ea);
                    }
                    int clickCount = 0;
                    if (button != MouseButtons.None)
                    {
                        clickCount = (param == WM_LBUTTONDBLCLK || param == WM_RBUTTONDBLCLK) ? 2 : 1;
                    }
                    var e = new MouseEventArgs(button, clickCount, mStruct.pt.x, mStruct.pt.y, delta);
                    // Raise Events.
                    if (OnMouseUp != null && (param == WM_LBUTTONUP || param == WM_MBUTTONUP || param == WM_RBUTTONUP || param == WM_XBUTTONUP || param == WM_NCXBUTTONUP))
                    {
                        OnMouseUp(this, e);
                    }
                    else if (OnMouseDown != null && (param == WM_LBUTTONDOWN || param == WM_MBUTTONDOWN || param == WM_RBUTTONDOWN || param == WM_XBUTTONDOWN || param == WM_NCXBUTTONDOWN))
                    {
                        OnMouseDown(this, e);
                    }
                    else if (OnMouseMove != null && (param == WM_MOUSEMOVE))
                    {
                        OnMouseMove(this, e);
                    }
                    else if (OnMouseWheel != null)
                    {
                        OnMouseWheel(this, e);
                    }
                    else if (OnMouseActivity != null)
                    {
                        OnMouseActivity(this, e);
                    }
                }
            }
            return(CallNextHookEx(hHook, nCode, wParam, lParam));
        }
예제 #43
0
 /// <summary>Initializes a new instance of the <see cref="T:System.ComponentModel.Win32Exception" /> class with the last Win32 error that occurred.</summary>
 public Win32Exception() : base(Win32Exception.W32ErrorMessage(Marshal.GetLastWin32Error()))
 {
     this.native_error_code = Marshal.GetLastWin32Error();
 }
예제 #44
0
 /// <summary>Initializes a new instance of the <see cref="T:System.ComponentModel.Win32Exception" /> class with the specified error.</summary>
 /// <param name="error">The Win32 error code associated with this exception. </param>
 public Win32Exception(int error) : base(Win32Exception.W32ErrorMessage(error))
 {
     this.native_error_code = error;
 }
예제 #45
0
    /// Intro to DCs:
    /// If you are familiar, skip ahead. If not, read on.
    /// Device contexts are just generic ways to represent devices,
    /// or things you can draw on or interact with graphically.
    /// This is hugely over simplified, and I'm going to get flamed, but for the sake of brevity,
    /// let's just go with that for now. You can get device context's, or dc's as
    /// they are commonly referred to, from images, windows, monitors, and even printers.
    /// Every window has them, and you can use them to draw with. Everything you see on your screen is being
    /// drawn upon a device context. The desktop, every window, your taskbar, and anything you see.
    /// You can draw upon them, or copy what they have drawn upon them. If you can get a hold of them,
    /// you can pretty much draw or steal whatever you want graphically speaking.
    /// Working with device contexts is fast, and both GDI and GDI+ are based on them.
    /// in the case of capturing the screen, we know that somewhere Windows is drawing upon a device context, so that we can see it.
    /// In fact, there's one for each monitor you have attached to your system, and that desktop that you are seeing on it,
    /// is being drawn on that monitor's device context.
    /// All we have to do is grab a hold of that device context, create another one of our own,
    /// and copy the screen's device context image data to our own, and we've got a screen capture


    public static Bitmap GetDesktopWindowCaptureAsBitmap()
    {
        //SEE HOW THIS FUNCTION WORKS AT THE END OF THIS FUNCTION.
        Rectangle rcScreen = Rectangle.Empty;

        Screen[] screens = Screen.AllScreens;


        // Create a rectangle encompassing all screens...
        foreach (Screen screen in Screen.AllScreens)
        {
            rcScreen = Rectangle.Union(rcScreen, screen.Bounds);
        }

        // Create a composite bitmap of the size of all screens...
        Bitmap finalBitmap = new Bitmap(rcScreen.Width, rcScreen.Height);

        // Get a graphics object for the composite bitmap and initialize it...
        Graphics g = Graphics.FromImage(finalBitmap);

        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
        g.FillRectangle(
            SystemBrushes.Desktop,
            0,
            0,
            rcScreen.Width - rcScreen.X,
            rcScreen.Height - rcScreen.Y);

        // Get an HDC for the composite area...
        IntPtr hdcDestination = g.GetHdc();

        // Now, loop through screens,
        // Blting each to the composite HDC created above...
        foreach (Screen screen in Screen.AllScreens)
        {
            // Create DC for each source monitor...
            IntPtr hdcSource = Win32.CreateDC(
                IntPtr.Zero,
                screen.DeviceName,
                IntPtr.Zero,
                IntPtr.Zero);

            // Blt the source directly to the composite destination...
            int xDest = screen.Bounds.X - rcScreen.X;
            int yDest = screen.Bounds.Y - rcScreen.Y;

            bool success = Win32.StretchBlt(
                hdcDestination,
                xDest,
                yDest,
                screen.Bounds.Width,
                screen.Bounds.Height,
                hdcSource,
                0,
                0,
                screen.Bounds.Width,
                screen.Bounds.Height,
                (int)Win32.TernaryRasterOperations.SRCCOPY);

            //  System.Diagnostics.Trace.WriteLine(screen.Bounds);

            if (!success)
            {
                System.ComponentModel.Win32Exception win32Exception =
                    new System.ComponentModel.Win32Exception();
                System.Diagnostics.Trace.WriteLine(win32Exception);
            }

            // Cleanup source HDC...
            Win32.DeleteDC(hdcSource);
        }

        // Cleanup destination HDC and Graphics...
        g.ReleaseHdc(hdcDestination);
        g.Dispose();

        // Return composite bitmap which will become our Form's PictureBox's image...
        return(finalBitmap);

        ///Looking at the code, the first thing you'll see is that I'm using a mixture of GDI and GDI+.
        ///This is due largely to the fact that there is a bug present in GDI+ and the BtBlt API.
        ///This issue only manifests itself on systems with multiple monitors, and if I remember correctly,
        ///the system had to have a NVida display adapter on the non-primary monitor, and of course, our old friend Windows 98 running as the OS.
        ///What happens is the primary monitor captures fine, the secondary (or any non-primary) monitor stands a chance of returning garbage for an image.
        ///It looks like cable channel with no signal.

        ///Instead of relying on purely managed code, do copy the images,
        ///or backing up to the BtBlt API, we instead fall back to it's somewhat slower cousin, StretchBlt.

        ///first up we just grab all of the monitors using the Screen class' AllScreens property.
        ///This does two things for us. First it allows us to figure out how big the entire desktop is,
        ///and create an image just big enough to hold all of the screens inside.
        ///And secondly, it allows us to figure out just where each monitor is positioned in relation to the other.
        ///Remember, with multiple monitor support you can "arrange" your monitors in different ways,
        ///and with different resolutions, so don't think in terms of a pure rectangle when you think of
        ///how your monitors are positioned.

        ///Once we have those screens, it's a trivial matter to calculate the size of the entire bitmap
        ///by using the Rectangle.Union method to build up the size of the overall image.
        ///After we've figured out the size of the final image, we'll grab a Graphics object from the image.
        ///The GDI+ Graphics object is just the .NET wrapper around a device context.
        ///Using that graphics context, we can draw on the bitmap with the graphics object.

        ///Next, we'll enumerate through each monitor, and draw what that monitor has on it's device context,
        ///upon the image we just created that will hold the final screen shot.
        ///Well draw it using it's coordinates so that in case the monitors have different resolutions or positioning
        ///we'll be able to see them as the Display Control Panel applet sees them.
        ///Go check it out if you have multiple monitors, and you didn't know you could move them.
        ///Chances are there if you have multiple monitors, you know this already, but if not so harm no foul.
        ///Open the settings tab and drag one of the monitors around and
        ///you'll see you can reposition it in relation to the other monitors.

        ///For each monitor, we'll simply use the StretchBlt API to copy that monitor's device context contents,
        ///to the bitmap that will serve as the screen capture of the desktop.
        ///Notice that I'm creating a device context each time, this gives us access to that monitor's device context so
        ///that we can copy from it. Keep in mind that if we create it, we must destroy it,
        ///so we delete the device context when we are finished with it. If you don't, you'll have a memory leak,
        ///so keep a watchful eye on your dc's and make sure to release or destroy them.
        ///A simple rule is, if you "acquire" it, you're required to "release" it.
        ///And if you "create" it, then you must "destroy" it.
        ///I quote those because if you look at the GDI APIs, with that in mind you'll find the necessary APIs to do exactly what you want.

        ///Finally, after copying the contents of each device context to that bitmap we created,
        ///we'll release the Graphics object we acquired from the bitmap, and dispose it.
        ///That's the proper way to clean up a graphics object, if you've acquired a device context from it.
    }
예제 #46
0
    public static string GetSystemMessage(uint errorCode)
    {
        var exception = new System.ComponentModel.Win32Exception((int)errorCode);

        return(exception.Message);
    }
예제 #47
0
 public Win32Exception(int error) : this(error, Win32Exception.GetErrorMessage(error))
 {
 }