diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index 46cb9547f..56698ec2d 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -60,7 +60,7 @@ namespace Greenshot.Drawing { } } - public virtual void Dispose() { + public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } diff --git a/Greenshot/Drawing/StepLabelContainer.cs b/Greenshot/Drawing/StepLabelContainer.cs index a33d6589c..acf3f93a6 100644 --- a/Greenshot/Drawing/StepLabelContainer.cs +++ b/Greenshot/Drawing/StepLabelContainer.cs @@ -133,7 +133,7 @@ namespace Greenshot.Drawing { /// /// Make sure this element is no longer referenced from the surface /// - public override void Dispose() { + public new void Dispose() { ((Surface)Parent).RemoveStepLabel(this); base.Dispose(); } diff --git a/Greenshot/Forms/AboutForm.cs b/Greenshot/Forms/AboutForm.cs index caded2080..dd594183b 100644 --- a/Greenshot/Forms/AboutForm.cs +++ b/Greenshot/Forms/AboutForm.cs @@ -317,7 +317,9 @@ namespace Greenshot { case Keys.L: try { if (File.Exists(MainForm.LogFileLocation)) { - Process.Start("\"" + MainForm.LogFileLocation + "\""); + using (Process.Start("\"" + MainForm.LogFileLocation + "\"")) { + // nothing to do, just using dispose to cleanup + } } else { MessageBox.Show("Greenshot can't find the logfile, it should have been here: " + MainForm.LogFileLocation); } @@ -327,7 +329,8 @@ namespace Greenshot { break; case Keys.I: try { - Process.Start("\"" + IniConfig.ConfigLocation + "\""); + using (Process.Start("\"" + IniConfig.ConfigLocation + "\"")) { + } } catch (Exception) { MessageBox.Show("Couldn't open the greenshot.ini, it's located here: " + IniConfig.ConfigLocation, "Error opening greeenshot.ini", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } diff --git a/Greenshot/Forms/ImageEditorForm.cs b/Greenshot/Forms/ImageEditorForm.cs index 79bd460a0..e8c8eeb31 100644 --- a/Greenshot/Forms/ImageEditorForm.cs +++ b/Greenshot/Forms/ImageEditorForm.cs @@ -925,9 +925,10 @@ namespace Greenshot { ProcessStartInfo psi = new ProcessStartInfo("explorer"); psi.Arguments = Path.GetDirectoryName(surface.LastSaveFullPath); psi.UseShellExecute = false; - Process p = new Process(); - p.StartInfo = psi; - p.Start(); + using (Process p = new Process()) { + p.StartInfo = psi; + p.Start(); + } } #endregion diff --git a/Greenshot/Forms/MainForm.cs b/Greenshot/Forms/MainForm.cs index 5197593ef..3a4e208bd 100644 --- a/Greenshot/Forms/MainForm.cs +++ b/Greenshot/Forms/MainForm.cs @@ -239,18 +239,25 @@ namespace Greenshot { StringBuilder instanceInfo = new StringBuilder(); bool matchedThisProcess = false; int index = 1; + int currentProcessId; + using (Process currentProcess = Process.GetCurrentProcess()) { + currentProcessId = currentProcess.Id; + } foreach (Process greenshotProcess in Process.GetProcessesByName("greenshot")) { try { - instanceInfo.Append(index++ + ": ").AppendLine(Kernel32.GetProcessPath(new IntPtr(greenshotProcess.Id))); - if (Process.GetCurrentProcess().Id == greenshotProcess.Id) { + instanceInfo.Append(index++ + ": ").AppendLine(Kernel32.GetProcessPath(greenshotProcess.Id)); + if (currentProcessId == greenshotProcess.Id) { matchedThisProcess = true; } } catch (Exception ex) { LOG.Debug(ex); } + greenshotProcess.Dispose(); } if (!matchedThisProcess) { - instanceInfo.Append(index + ": ").AppendLine(Kernel32.GetProcessPath(new IntPtr(Process.GetCurrentProcess().Id))); + using (Process currentProcess = Process.GetCurrentProcess()) { + instanceInfo.Append(index + ": ").AppendLine(Kernel32.GetProcessPath(currentProcess.Id)); + } } MessageBox.Show(Language.GetString(LangKey.error_multipleinstances) + "\r\n" + instanceInfo, Language.GetString(LangKey.error)); } @@ -1249,7 +1256,8 @@ namespace Greenshot { if (path != null) { try { - Process.Start(path); + using (Process process = Process.Start(path)) { + } } catch (Exception ex) { // Make sure we show what we tried to open in the exception ex.Data.Add("path", path); @@ -1382,7 +1390,9 @@ namespace Greenshot { private void BackgroundWorkerTimerTick(object sender, EventArgs e) { if (_conf.MinimizeWorkingSetSize) { LOG.Info("Calling EmptyWorkingSet"); - PsAPI.EmptyWorkingSet(Process.GetCurrentProcess().Handle); + using (Process currentProcess = Process.GetCurrentProcess()) { + PsAPI.EmptyWorkingSet(currentProcess.Handle); + } } if (UpdateHelper.IsUpdateCheckNeeded()) { LOG.Debug("BackgroundWorkerTimerTick checking for update"); diff --git a/Greenshot/Helpers/CaptureHelper.cs b/Greenshot/Helpers/CaptureHelper.cs index 97fec59e4..30c25f962 100644 --- a/Greenshot/Helpers/CaptureHelper.cs +++ b/Greenshot/Helpers/CaptureHelper.cs @@ -596,9 +596,10 @@ namespace Greenshot.Helpers { ProcessStartInfo psi = new ProcessStartInfo("explorer.exe"); psi.Arguments = Path.GetDirectoryName(surface.LastSaveFullPath); psi.UseShellExecute = false; - Process p = new Process(); - p.StartInfo = psi; - p.Start(); + using (Process p = new Process()) { + p.StartInfo = psi; + p.Start(); + } } catch (Exception ex) { errorMessage = ex.Message; } @@ -611,9 +612,10 @@ namespace Greenshot.Helpers { ProcessStartInfo psi = new ProcessStartInfo(explorerPath); psi.Arguments = Path.GetDirectoryName(surface.LastSaveFullPath); psi.UseShellExecute = false; - Process p = new Process(); - p.StartInfo = psi; - p.Start(); + using (Process p = new Process()) { + p.StartInfo = psi; + p.Start(); + } errorMessage = null; } } catch { @@ -783,151 +785,152 @@ namespace Greenshot.Helpers { // When Vista & DWM (Aero) enabled bool dwmEnabled = DWM.isDWMEnabled(); // get process name to be able to exclude certain processes from certain capture modes - Process process = windowToCapture.Process; - bool isAutoMode = windowCaptureMode == WindowCaptureMode.Auto; - // For WindowCaptureMode.Auto we check: - // 1) Is window IE, use IE Capture - // 2) Is Windows >= Vista & DWM enabled: use DWM - // 3) Otherwise use GDI (Screen might be also okay but might lose content) - if (isAutoMode) { - if (conf.IECapture && IECaptureHelper.IsIEWindow(windowToCapture)) { - try { - ICapture ieCapture = IECaptureHelper.CaptureIE(captureForWindow, windowToCapture); - if (ieCapture != null) { - return ieCapture; + using (Process process = windowToCapture.Process) { + bool isAutoMode = windowCaptureMode == WindowCaptureMode.Auto; + // For WindowCaptureMode.Auto we check: + // 1) Is window IE, use IE Capture + // 2) Is Windows >= Vista & DWM enabled: use DWM + // 3) Otherwise use GDI (Screen might be also okay but might lose content) + if (isAutoMode) { + if (conf.IECapture && IECaptureHelper.IsIEWindow(windowToCapture)) { + try { + ICapture ieCapture = IECaptureHelper.CaptureIE(captureForWindow, windowToCapture); + if (ieCapture != null) { + return ieCapture; + } + } catch (Exception ex) { + LOG.WarnFormat("Problem capturing IE, skipping to normal capture. Exception message was: {0}", ex.Message); } - } catch (Exception ex) { - LOG.WarnFormat("Problem capturing IE, skipping to normal capture. Exception message was: {0}", ex.Message); } - } - - // Take default screen - windowCaptureMode = WindowCaptureMode.Screen; - - // Change to GDI, if allowed - if (!windowToCapture.isMetroApp && WindowCapture.isGDIAllowed(process)) { - if (!dwmEnabled && isWPF(process)) { - // do not use GDI, as DWM is not enabled and the application uses PresentationFramework.dll -> isWPF - LOG.InfoFormat("Not using GDI for windows of process {0}, as the process uses WPF", process.ProcessName); - } else { - windowCaptureMode = WindowCaptureMode.GDI; - } - } - // Change to DWM, if enabled and allowed - if (dwmEnabled) { - if (windowToCapture.isMetroApp || WindowCapture.isDWMAllowed(process)) { - windowCaptureMode = WindowCaptureMode.Aero; - } - } - } else if (windowCaptureMode == WindowCaptureMode.Aero || windowCaptureMode == WindowCaptureMode.AeroTransparent) { - if (!dwmEnabled || (!windowToCapture.isMetroApp && !WindowCapture.isDWMAllowed(process))) { // Take default screen windowCaptureMode = WindowCaptureMode.Screen; - // Change to GDI, if allowed - if (WindowCapture.isGDIAllowed(process)) { - windowCaptureMode = WindowCaptureMode.GDI; - } - } - } else if (windowCaptureMode == WindowCaptureMode.GDI && !WindowCapture.isGDIAllowed(process)) { - // GDI not allowed, take screen - windowCaptureMode = WindowCaptureMode.Screen; - } - LOG.InfoFormat("Capturing window with mode {0}", windowCaptureMode); - bool captureTaken = false; - windowRectangle.Intersect(captureForWindow.ScreenBounds); - // Try to capture - while (!captureTaken) { - ICapture tmpCapture = null; - switch (windowCaptureMode) { - case WindowCaptureMode.GDI: + // Change to GDI, if allowed + if (!windowToCapture.isMetroApp && WindowCapture.isGDIAllowed(process)) { + if (!dwmEnabled && isWPF(process)) { + // do not use GDI, as DWM is not enabled and the application uses PresentationFramework.dll -> isWPF + LOG.InfoFormat("Not using GDI for windows of process {0}, as the process uses WPF", process.ProcessName); + } else { + windowCaptureMode = WindowCaptureMode.GDI; + } + } + + // Change to DWM, if enabled and allowed + if (dwmEnabled) { + if (windowToCapture.isMetroApp || WindowCapture.isDWMAllowed(process)) { + windowCaptureMode = WindowCaptureMode.Aero; + } + } + } else if (windowCaptureMode == WindowCaptureMode.Aero || windowCaptureMode == WindowCaptureMode.AeroTransparent) { + if (!dwmEnabled || (!windowToCapture.isMetroApp && !WindowCapture.isDWMAllowed(process))) { + // Take default screen + windowCaptureMode = WindowCaptureMode.Screen; + // Change to GDI, if allowed if (WindowCapture.isGDIAllowed(process)) { + windowCaptureMode = WindowCaptureMode.GDI; + } + } + } else if (windowCaptureMode == WindowCaptureMode.GDI && !WindowCapture.isGDIAllowed(process)) { + // GDI not allowed, take screen + windowCaptureMode = WindowCaptureMode.Screen; + } + + LOG.InfoFormat("Capturing window with mode {0}", windowCaptureMode); + bool captureTaken = false; + windowRectangle.Intersect(captureForWindow.ScreenBounds); + // Try to capture + while (!captureTaken) { + ICapture tmpCapture = null; + switch (windowCaptureMode) { + case WindowCaptureMode.GDI: + if (WindowCapture.isGDIAllowed(process)) { + if (windowToCapture.Iconic) { + // Restore the window making sure it's visible! + windowToCapture.Restore(); + } else { + windowToCapture.ToForeground(); + } + tmpCapture = windowToCapture.CaptureGDIWindow(captureForWindow); + if (tmpCapture != null) { + // check if GDI capture any good, by comparing it with the screen content + int blackCountGDI = ImageHelper.CountColor((Bitmap)tmpCapture.Image, Color.Black, false); + int GDIPixels = tmpCapture.Image.Width * tmpCapture.Image.Height; + int blackPercentageGDI = (blackCountGDI * 100) / GDIPixels; + if (blackPercentageGDI >= 1) { + int screenPixels = windowRectangle.Width * windowRectangle.Height; + using (ICapture screenCapture = new Capture()) { + screenCapture.CaptureDetails = captureForWindow.CaptureDetails; + if (WindowCapture.CaptureRectangle(screenCapture, windowRectangle) != null) { + int blackCountScreen = ImageHelper.CountColor((Bitmap)screenCapture.Image, Color.Black, false); + int blackPercentageScreen = (blackCountScreen * 100) / screenPixels; + if (screenPixels == GDIPixels) { + // "easy compare", both have the same size + // If GDI has more black, use the screen capture. + if (blackPercentageGDI > blackPercentageScreen) { + LOG.Debug("Using screen capture, as GDI had additional black."); + // changeing the image will automatically dispose the previous + tmpCapture.Image = screenCapture.Image; + // Make sure it's not disposed, else the picture is gone! + screenCapture.NullImage(); + } + } else if (screenPixels < GDIPixels) { + // Screen capture is cropped, window is outside of screen + if (blackPercentageGDI > 50 && blackPercentageGDI > blackPercentageScreen) { + LOG.Debug("Using screen capture, as GDI had additional black."); + // changeing the image will automatically dispose the previous + tmpCapture.Image = screenCapture.Image; + // Make sure it's not disposed, else the picture is gone! + screenCapture.NullImage(); + } + } else { + // Use the GDI capture by doing nothing + LOG.Debug("This should not happen, how can there be more screen as GDI pixels?"); + } + } + } + } + } + } + if (tmpCapture != null) { + captureForWindow = tmpCapture; + captureTaken = true; + } else { + // A problem, try Screen + windowCaptureMode = WindowCaptureMode.Screen; + } + break; + case WindowCaptureMode.Aero: + case WindowCaptureMode.AeroTransparent: + if (windowToCapture.isMetroApp || WindowCapture.isDWMAllowed(process)) { + tmpCapture = windowToCapture.CaptureDWMWindow(captureForWindow, windowCaptureMode, isAutoMode); + } + if (tmpCapture != null) { + captureForWindow = tmpCapture; + captureTaken = true; + } else { + // A problem, try GDI + windowCaptureMode = WindowCaptureMode.GDI; + } + break; + default: + // Screen capture if (windowToCapture.Iconic) { // Restore the window making sure it's visible! windowToCapture.Restore(); } else { windowToCapture.ToForeground(); } - tmpCapture = windowToCapture.CaptureGDIWindow(captureForWindow); - if (tmpCapture != null) { - // check if GDI capture any good, by comparing it with the screen content - int blackCountGDI = ImageHelper.CountColor((Bitmap)tmpCapture.Image, Color.Black, false); - int GDIPixels = tmpCapture.Image.Width * tmpCapture.Image.Height; - int blackPercentageGDI = (blackCountGDI * 100) / GDIPixels; - if (blackPercentageGDI >= 1) { - int screenPixels = windowRectangle.Width * windowRectangle.Height; - using (ICapture screenCapture = new Capture()) { - screenCapture.CaptureDetails = captureForWindow.CaptureDetails; - if (WindowCapture.CaptureRectangle(screenCapture, windowRectangle) != null) { - int blackCountScreen = ImageHelper.CountColor((Bitmap)screenCapture.Image, Color.Black, false); - int blackPercentageScreen = (blackCountScreen * 100) / screenPixels; - if (screenPixels == GDIPixels) { - // "easy compare", both have the same size - // If GDI has more black, use the screen capture. - if (blackPercentageGDI > blackPercentageScreen) { - LOG.Debug("Using screen capture, as GDI had additional black."); - // changeing the image will automatically dispose the previous - tmpCapture.Image = screenCapture.Image; - // Make sure it's not disposed, else the picture is gone! - screenCapture.NullImage(); - } - } else if (screenPixels < GDIPixels) { - // Screen capture is cropped, window is outside of screen - if (blackPercentageGDI > 50 && blackPercentageGDI > blackPercentageScreen) { - LOG.Debug("Using screen capture, as GDI had additional black."); - // changeing the image will automatically dispose the previous - tmpCapture.Image = screenCapture.Image; - // Make sure it's not disposed, else the picture is gone! - screenCapture.NullImage(); - } - } else { - // Use the GDI capture by doing nothing - LOG.Debug("This should not happen, how can there be more screen as GDI pixels?"); - } - } - } - } - } - } - if (tmpCapture != null) { - captureForWindow = tmpCapture; - captureTaken = true; - } else { - // A problem, try Screen - windowCaptureMode = WindowCaptureMode.Screen; - } - break; - case WindowCaptureMode.Aero: - case WindowCaptureMode.AeroTransparent: - if (windowToCapture.isMetroApp || WindowCapture.isDWMAllowed(process)) { - tmpCapture = windowToCapture.CaptureDWMWindow(captureForWindow, windowCaptureMode, isAutoMode); - } - if (tmpCapture != null) { - captureForWindow = tmpCapture; - captureTaken = true; - } else { - // A problem, try GDI - windowCaptureMode = WindowCaptureMode.GDI; - } - break; - default: - // Screen capture - if (windowToCapture.Iconic) { - // Restore the window making sure it's visible! - windowToCapture.Restore(); - } else { - windowToCapture.ToForeground(); - } - try { - captureForWindow = WindowCapture.CaptureRectangle(captureForWindow, windowRectangle); - captureTaken = true; - } catch (Exception e) { - LOG.Error("Problem capturing", e); - return null; - } - break; + try { + captureForWindow = WindowCapture.CaptureRectangle(captureForWindow, windowRectangle); + captureTaken = true; + } catch (Exception e) { + LOG.Error("Problem capturing", e); + return null; + } + break; + } } } diff --git a/Greenshot/Helpers/CopyData.cs b/Greenshot/Helpers/CopyData.cs index 99d9628cf..d1d00e805 100644 --- a/Greenshot/Helpers/CopyData.cs +++ b/Greenshot/Helpers/CopyData.cs @@ -191,7 +191,7 @@ namespace Greenshot.Helpers { /// Contains data and other information associated with data /// which has been sent from another application. /// - public class CopyDataReceivedEventArgs { + public class CopyDataReceivedEventArgs : EventArgs { private string channelName = ""; private object data = null; private DateTime sent; @@ -365,12 +365,12 @@ namespace Greenshot.Helpers { [DllImport("user32", CharSet=CharSet.Unicode, SetLastError = true)] private extern static IntPtr GetProp(IntPtr hwnd, string lpString); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static IntPtr SetProp(IntPtr hwnd, string lpString, int hData); + private extern static bool SetProp(IntPtr hwnd, string lpString, IntPtr hData); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] private extern static IntPtr RemoveProp(IntPtr hwnd, string lpString); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static IntPtr SendMessage(IntPtr hwnd, int wMsg, int wParam, ref COPYDATASTRUCT lParam); + private extern static IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam); [StructLayout(LayoutKind.Sequential)] private struct COPYDATASTRUCT { @@ -448,7 +448,7 @@ namespace Greenshot.Helpers { cds.cbData = dataSize; cds.dwData = IntPtr.Zero; cds.lpData = ptrData; - SendMessage(window.Handle, WM_COPYDATA, (int)owner.Handle, ref cds); + SendMessage(window.Handle, WM_COPYDATA, owner.Handle, ref cds); recipients += (Marshal.GetLastWin32Error() == 0 ? 1 : 0); } } @@ -464,7 +464,7 @@ namespace Greenshot.Helpers { private void addChannel() { // Tag this window with property "channelName" - SetProp(owner.Handle, channelName, (int)owner.Handle); + SetProp(owner.Handle, channelName, owner.Handle); } private void removeChannel() { @@ -515,7 +515,7 @@ namespace Greenshot.Helpers { } ~CopyDataChannel() { - Dispose(); + Dispose(false); } } diff --git a/Greenshot/Helpers/MailHelper.cs b/Greenshot/Helpers/MailHelper.cs index e5fad7bc2..4c7317545 100644 --- a/Greenshot/Helpers/MailHelper.cs +++ b/Greenshot/Helpers/MailHelper.cs @@ -504,7 +504,7 @@ namespace Greenshot.Helpers { public IntPtr EntryID = IntPtr.Zero; } - [DllImport("MAPI32.DLL", SetLastError = true)] + [DllImport("MAPI32.DLL", SetLastError = true, CharSet=CharSet.Unicode)] public static extern int MAPISendMail(IntPtr session, IntPtr hwnd, MapiMessage message, int flg, int rsv); #endregion Structs diff --git a/GreenshotExternalCommandPlugin/ExternalCommandDestination.cs b/GreenshotExternalCommandPlugin/ExternalCommandDestination.cs index 00c7ff8f4..b8ae93598 100644 --- a/GreenshotExternalCommandPlugin/ExternalCommandDestination.cs +++ b/GreenshotExternalCommandPlugin/ExternalCommandDestination.cs @@ -128,23 +128,24 @@ namespace ExternalCommand { string arguments = config.arguments[commando]; output = null; if (commandline != null && commandline.Length > 0) { - Process p = new Process(); - p.StartInfo.FileName = commandline; - p.StartInfo.Arguments = String.Format(arguments, fullPath); - p.StartInfo.UseShellExecute = false; - p.StartInfo.RedirectStandardOutput = true; - if (verb != null) { - p.StartInfo.Verb = verb; + using (Process p = new Process()) { + p.StartInfo.FileName = commandline; + p.StartInfo.Arguments = String.Format(arguments, fullPath); + p.StartInfo.UseShellExecute = false; + p.StartInfo.RedirectStandardOutput = true; + if (verb != null) { + p.StartInfo.Verb = verb; + } + LOG.Info("Starting : " + p.StartInfo.FileName + " " + p.StartInfo.Arguments); + p.Start(); + p.WaitForExit(); + output = p.StandardOutput.ReadToEnd(); + if (output != null && output.Trim().Length > 0) { + LOG.Info("Output:\n" + output); + } + LOG.Info("Finished : " + p.StartInfo.FileName + " " + p.StartInfo.Arguments); + return p.ExitCode; } - LOG.Info("Starting : " + p.StartInfo.FileName + " " + p.StartInfo.Arguments); - p.Start(); - p.WaitForExit(); - output = p.StandardOutput.ReadToEnd(); - if (output != null && output.Trim().Length > 0) { - LOG.Info("Output:\n" + output); - } - LOG.Info("Finished : " + p.StartInfo.FileName + " " + p.StartInfo.Arguments); - return p.ExitCode; } return -1; } diff --git a/GreenshotOCRPlugin/OCRPlugin.cs b/GreenshotOCRPlugin/OCRPlugin.cs index 60d723435..e13ad5048 100644 --- a/GreenshotOCRPlugin/OCRPlugin.cs +++ b/GreenshotOCRPlugin/OCRPlugin.cs @@ -182,10 +182,11 @@ namespace GreenshotOCR { processStartInfo.CreateNoWindow = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.UseShellExecute = false; - Process process = Process.Start(processStartInfo); - process.WaitForExit(30*1000); - if (process.ExitCode == 0) { - text = process.StandardOutput.ReadToEnd(); + using (Process process = Process.Start(processStartInfo)) { + process.WaitForExit(30 * 1000); + if (process.ExitCode == 0) { + text = process.StandardOutput.ReadToEnd(); + } } } catch (Exception e) { LOG.Error("Error while calling Microsoft Office Document Imaging (MODI) to OCR: ", e); @@ -215,10 +216,10 @@ namespace GreenshotOCR { private bool HasMODI() { try { - Process process = Process.Start(OCR_COMMAND, "-c"); - process.WaitForExit(); - int errorCode = process.ExitCode; - return errorCode == 0; + using (Process process = Process.Start(OCR_COMMAND, "-c")) { + process.WaitForExit(); + return process.ExitCode == 0; + } } catch(Exception e) { LOG.DebugFormat("Error trying to initiate MODI: {0}", e.Message); } diff --git a/GreenshotPlugin/Core/ClipboardHelper.cs b/GreenshotPlugin/Core/ClipboardHelper.cs index 2aa361a49..a786872da 100644 --- a/GreenshotPlugin/Core/ClipboardHelper.cs +++ b/GreenshotPlugin/Core/ClipboardHelper.cs @@ -100,18 +100,19 @@ EndSelection:<<<<<<<4 try { IntPtr hWnd = User32.GetClipboardOwner(); if (hWnd != IntPtr.Zero) { - IntPtr pid = IntPtr.Zero; - IntPtr tid = User32.GetWindowThreadProcessId( hWnd, out pid); - Process me = Process.GetCurrentProcess(); - Process ownerProcess = Process.GetProcessById( pid.ToInt32() ); - // Exclude myself - if (ownerProcess != null && me.Id != ownerProcess.Id) { - // Get Process Name - owner = ownerProcess.ProcessName; - // Try to get the starting Process Filename, this might fail. - try { - owner = ownerProcess.Modules[0].FileName; - } catch (Exception) { + int pid; + User32.GetWindowThreadProcessId( hWnd, out pid); + using (Process me = Process.GetCurrentProcess()) + using (Process ownerProcess = Process.GetProcessById(pid)) { + // Exclude myself + if (ownerProcess != null && me.Id != ownerProcess.Id) { + // Get Process Name + owner = ownerProcess.ProcessName; + // Try to get the starting Process Filename, this might fail. + try { + owner = ownerProcess.Modules[0].FileName; + } catch (Exception) { + } } } } diff --git a/GreenshotPlugin/Core/EncryptionHelper.cs b/GreenshotPlugin/Core/EncryptionHelper.cs index 91dbfeca8..6c2bff6e4 100644 --- a/GreenshotPlugin/Core/EncryptionHelper.cs +++ b/GreenshotPlugin/Core/EncryptionHelper.cs @@ -44,12 +44,12 @@ namespace GreenshotPlugin.Core { using (MemoryStream ms = new MemoryStream()) { byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV); byte[] key = Encoding.ASCII.GetBytes(KEY); - CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); - - cs.Write(clearTextBytes, 0, clearTextBytes.Length); - - cs.Close(); - returnValue = Convert.ToBase64String(ms.ToArray()); + using (CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write)) { + cs.Write(clearTextBytes, 0, clearTextBytes.Length); + cs.FlushFinalBlock(); + + returnValue = Convert.ToBase64String(ms.ToArray()); + } } } catch (Exception ex) { LOG.ErrorFormat("Error encrypting, error: ", ex.Message); @@ -72,14 +72,13 @@ namespace GreenshotPlugin.Core { byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV); byte[] key = Encoding.ASCII.GetBytes(KEY); + + using (CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write)) { + cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); + cs.FlushFinalBlock(); + returnValue = Encoding.ASCII.GetString(ms.ToArray()); + } - CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), - CryptoStreamMode.Write); - - cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); - - cs.Close(); - returnValue = Encoding.ASCII.GetString(ms.ToArray()); } } catch (Exception ex) { LOG.ErrorFormat("Error decrypting {0}, error: ", EncryptedText, ex.Message); diff --git a/GreenshotPlugin/Core/ImageOutput.cs b/GreenshotPlugin/Core/ImageOutput.cs index d4a8deb14..0d7bc1ff7 100644 --- a/GreenshotPlugin/Core/ImageOutput.cs +++ b/GreenshotPlugin/Core/ImageOutput.cs @@ -250,21 +250,22 @@ namespace GreenshotPlugin.Core { processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; processStartInfo.UseShellExecute = false; - Process process = Process.Start(processStartInfo); - if (process != null) { - process.WaitForExit(); - if (process.ExitCode == 0) { - if (LOG.IsDebugEnabled) { - LOG.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length); - LOG.DebugFormat("Reading back tmp file: {0}", tmpFileName); + using (Process process = Process.Start(processStartInfo)) { + if (process != null) { + process.WaitForExit(); + if (process.ExitCode == 0) { + if (LOG.IsDebugEnabled) { + LOG.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length); + LOG.DebugFormat("Reading back tmp file: {0}", tmpFileName); + } + byte[] processedImage = File.ReadAllBytes(tmpFileName); + targetStream.Write(processedImage, 0, processedImage.Length); + return true; } - byte[] processedImage = File.ReadAllBytes(tmpFileName); - targetStream.Write(processedImage, 0, processedImage.Length); - return true; + LOG.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode); + LOG.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd()); + LOG.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd()); } - LOG.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode); - LOG.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd()); - LOG.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd()); } } catch (Exception e) { LOG.Error("Error while processing PNG image: ", e); diff --git a/GreenshotPlugin/Core/Language.cs b/GreenshotPlugin/Core/Language.cs index 8e7773699..95d53e1c4 100644 --- a/GreenshotPlugin/Core/Language.cs +++ b/GreenshotPlugin/Core/Language.cs @@ -427,14 +427,14 @@ namespace GreenshotPlugin.Core { foreach (LanguageFile deleteFile in deleteList) { currentFiles.Remove(deleteFile); } - LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath); + LOG.InfoFormat("Added language definition {0} from: {1}", languageFile.Description, languageFile.Filepath); currentFiles.Add(languageFile); } } else { currentFiles = new List(); currentFiles.Add(languageFile); languageFiles.Add(languageFile.Ietf, currentFiles); - LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath); + LOG.InfoFormat("Added language definition {0} from: {1}", languageFile.Description, languageFile.Filepath); } } } catch (DirectoryNotFoundException) { diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 47be6adab..305131c4b 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -91,7 +91,7 @@ namespace GreenshotPlugin.Core { public WindowsEnumerator GetWindows(IntPtr hWndParent, string classname) { items = new List(); List windows = new List(); - User32.EnumChildWindows(hWndParent, new EnumWindowsProc(WindowEnum), 0); + User32.EnumChildWindows(hWndParent, new EnumWindowsProc(WindowEnum), IntPtr.Zero); bool hasParent = !IntPtr.Zero.Equals(hWndParent); string parentText = null; @@ -161,7 +161,6 @@ namespace GreenshotPlugin.Core { /// Provides details about a Window returned by the /// enumeration /// - [SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] public class WindowDetails : IEquatable{ private const string METRO_WINDOWS_CLASS = "Windows.UI.Core.CoreWindow"; private const string METRO_APPLAUNCHER_CLASS = "ImmersiveLauncher"; @@ -281,7 +280,7 @@ namespace GreenshotPlugin.Core { return string.Empty; } // Get the process id - IntPtr processid; + int processid; User32.GetWindowThreadProcessId(Handle, out processid); return Kernel32.GetProcessPath(processid); } @@ -730,10 +729,10 @@ namespace GreenshotPlugin.Core { return parentHandle != IntPtr.Zero; } } - - public IntPtr ProcessId { + + public int ProcessId { get { - IntPtr processId; + int processId; User32.GetWindowThreadProcessId(Handle, out processId); return processId; } @@ -742,9 +741,9 @@ namespace GreenshotPlugin.Core { public Process Process { get { try { - IntPtr processId; + int processId; User32.GetWindowThreadProcessId(Handle, out processId); - Process process = Process.GetProcessById(processId.ToInt32()); + Process process = Process.GetProcessById(processId); if (process != null) { return process; } @@ -866,7 +865,7 @@ namespace GreenshotPlugin.Core { return (WindowStyleFlags)User32.GetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_STYLE); } set { - User32.SetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_STYLE, (uint)value); + User32.SetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_STYLE, new IntPtr((uint)value)); } } @@ -892,7 +891,7 @@ namespace GreenshotPlugin.Core { return (ExtendedWindowStyleFlags)User32.GetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_EXSTYLE); } set { - User32.SetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_EXSTYLE, (uint)value); + User32.SetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_EXSTYLE, new IntPtr((uint)value)); } } @@ -992,9 +991,11 @@ namespace GreenshotPlugin.Core { // check if the capture fits if (!doesCaptureFit) { // if GDI is allowed.. (a screenshot won't be better than we comes if we continue) - if (!isMetroApp && WindowCapture.isGDIAllowed(Process)) { - // we return null which causes the capturing code to try another method. - return null; + using (Process thisWindowProcess = Process) { + if (!isMetroApp && WindowCapture.isGDIAllowed(thisWindowProcess)) { + // we return null which causes the capturing code to try another method. + return null; + } } } } @@ -1292,28 +1293,30 @@ namespace GreenshotPlugin.Core { /// Warning: Use only if no other way!! /// private bool FreezeWindow() { - Process proc = Process.GetProcessById(ProcessId.ToInt32()); - string processName = proc.ProcessName; - if (!CanFreezeOrUnfreeze(processName)) { - LOG.DebugFormat("Not freezing {0}", processName); - return false; - } - if (!CanFreezeOrUnfreeze(Text)) { - LOG.DebugFormat("Not freezing {0}", processName); - return false; - } - LOG.DebugFormat("Freezing process: {0}", processName); - bool frozen = false; - - foreach (ProcessThread pT in proc.Threads) { - IntPtr pOpenThread = Kernel32.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); - - if (pOpenThread == IntPtr.Zero) { - break; + using (Process proc = Process.GetProcessById(ProcessId)) { + string processName = proc.ProcessName; + if (!CanFreezeOrUnfreeze(processName)) { + LOG.DebugFormat("Not freezing {0}", processName); + return false; + } + if (!CanFreezeOrUnfreeze(Text)) { + LOG.DebugFormat("Not freezing {0}", processName); + return false; + } + LOG.DebugFormat("Freezing process: {0}", processName); + + + foreach (ProcessThread pT in proc.Threads) { + IntPtr pOpenThread = Kernel32.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); + + if (pOpenThread == IntPtr.Zero) { + break; + } + frozen = true; + Kernel32.SuspendThread(pOpenThread); + pT.Dispose(); } - frozen = true; - Kernel32.SuspendThread(pOpenThread); } return frozen; } @@ -1322,27 +1325,27 @@ namespace GreenshotPlugin.Core { /// Unfreeze the process belonging to the window /// public void UnfreezeWindow() { - Process proc = Process.GetProcessById(ProcessId.ToInt32()); - - string processName = proc.ProcessName; - if (!CanFreezeOrUnfreeze(processName)) { - LOG.DebugFormat("Not unfreezing {0}", processName); - return; - } - if (!CanFreezeOrUnfreeze(Text)) { - LOG.DebugFormat("Not unfreezing {0}", processName); - return; - } - LOG.DebugFormat("Unfreezing process: {0}", processName); - - foreach (ProcessThread pT in proc.Threads) { - IntPtr pOpenThread = Kernel32.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); - - if (pOpenThread == IntPtr.Zero) { - break; + using (Process proc = Process.GetProcessById(ProcessId)) { + string processName = proc.ProcessName; + if (!CanFreezeOrUnfreeze(processName)) { + LOG.DebugFormat("Not unfreezing {0}", processName); + return; + } + if (!CanFreezeOrUnfreeze(Text)) { + LOG.DebugFormat("Not unfreezing {0}", processName); + return; + } + LOG.DebugFormat("Unfreezing process: {0}", processName); + + foreach (ProcessThread pT in proc.Threads) { + IntPtr pOpenThread = Kernel32.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); + + if (pOpenThread == IntPtr.Zero) { + break; + } + + Kernel32.ResumeThread(pOpenThread); } - - Kernel32.ResumeThread(pOpenThread); } } @@ -1363,15 +1366,12 @@ namespace GreenshotPlugin.Core { } returnImage = new Bitmap(windowRect.Width, windowRect.Height, pixelFormat); using (Graphics graphics = Graphics.FromImage(returnImage)) { - IntPtr hDCDest = graphics.GetHdc(); - try { - bool printSucceeded = User32.PrintWindow(Handle, hDCDest, 0x0); + using (SafeDeviceContextHandle graphicsDC = graphics.getSafeDeviceContext()) { + bool printSucceeded = User32.PrintWindow(Handle, graphicsDC.DangerousGetHandle(), 0x0); if (!printSucceeded) { // something went wrong, most likely a "0x80004005" (Acess Denied) when using UAC exceptionOccured = User32.CreateWin32Exception("PrintWindow"); } - } finally { - graphics.ReleaseHdc(hDCDest); } // Apply the region "transparency" @@ -1439,7 +1439,9 @@ namespace GreenshotPlugin.Core { get { try { if (!isMetroApp) { - return "Greenshot".Equals(Process.MainModule.FileVersionInfo.ProductName); + using (Process thisWindowProcess = Process) { + return "Greenshot".Equals(thisWindowProcess.MainModule.FileVersionInfo.ProductName); + } } } catch (Exception ex) { LOG.Warn(ex); @@ -1622,7 +1624,7 @@ namespace GreenshotPlugin.Core { /// /// public static WindowDetails GetLinkedWindow(WindowDetails windowToLinkTo) { - IntPtr processIdSelectedWindow = windowToLinkTo.ProcessId; + int processIdSelectedWindow = windowToLinkTo.ProcessId; foreach(WindowDetails window in GetAllWindows()) { // Ignore windows without title if (window.Text.Length == 0) { diff --git a/GreenshotPlugin/Interfaces/Generic.cs b/GreenshotPlugin/Interfaces/Generic.cs index db147c696..5ca4b5d04 100644 --- a/GreenshotPlugin/Interfaces/Generic.cs +++ b/GreenshotPlugin/Interfaces/Generic.cs @@ -71,10 +71,10 @@ namespace Greenshot.Plugin { } } - public delegate void SurfaceSizeChangeEventHandler(object sender, EventArgs eventArgs); - public delegate void SurfaceMessageEventHandler(object sender, SurfaceMessageEventArgs eventArgs); - public delegate void SurfaceElementEventHandler(object sender, SurfaceElementEventArgs eventArgs); - public delegate void SurfaceDrawingModeEventHandler(object sender, SurfaceDrawingModeEventArgs eventArgs); + public delegate void SurfaceSizeChangeEventHandler(object sender, EventArgs e); + public delegate void SurfaceMessageEventHandler(object sender, SurfaceMessageEventArgs e); + public delegate void SurfaceElementEventHandler(object sender, SurfaceElementEventArgs e); + public delegate void SurfaceDrawingModeEventHandler(object sender, SurfaceDrawingModeEventArgs e); public enum DrawingModes { None, Rect, diff --git a/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs b/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs index 6c84b3b74..37a20ced1 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs @@ -56,12 +56,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("kernel32", SetLastError = true)] public static extern int ResumeThread(IntPtr hThread); [DllImport("kernel32", SetLastError = true)] - public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, IntPtr dwProcessId); - [DllImport("kernel32", SetLastError = true)] + public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, int dwProcessId); + [DllImport("kernel32", SetLastError = true, CharSet=CharSet.Unicode)] public static extern bool QueryFullProcessImageName(IntPtr hProcess, uint dwFlags, StringBuilder lpExeName, ref uint lpdwSize); - [DllImport("kernel32", SetLastError = true)] + [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, uint uuchMax); - [DllImport("kernel32", SetLastError = true)] + [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32", SetLastError = true)] public static extern bool CloseHandle(IntPtr hObject); @@ -71,7 +71,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// /// - public static string GetProcessPath(IntPtr processid) { + public static string GetProcessPath(int processid) { StringBuilder _PathBuffer = new StringBuilder(512); // Try the GetModuleFileName method first since it's the fastest. // May return ACCESS_DENIED (due to VM_READ flag) if the process is not owned by the current user. diff --git a/GreenshotPlugin/UnmanagedHelpers/PsAPI.cs b/GreenshotPlugin/UnmanagedHelpers/PsAPI.cs index e30a2de2f..64e5db998 100644 --- a/GreenshotPlugin/UnmanagedHelpers/PsAPI.cs +++ b/GreenshotPlugin/UnmanagedHelpers/PsAPI.cs @@ -27,9 +27,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// Description of PsAPI. /// public class PsAPI { - [DllImport("psapi", SetLastError = true)] + [DllImport("psapi", SetLastError = true, CharSet=CharSet.Unicode)] public static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, StringBuilder lpFilename, uint nSize); - [DllImport("psapi", SetLastError = true)] + [DllImport("psapi", SetLastError = true, CharSet = CharSet.Unicode)] public static extern uint GetProcessImageFileName(IntPtr hProcess, StringBuilder lpImageFileName, uint nSize); [DllImport("psapi")] public static extern int EmptyWorkingSet(IntPtr hwProc); diff --git a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs index 95a8c4a1c..7ef749ca4 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs @@ -29,9 +29,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// Description of Shell32. /// public static class Shell32 { - [DllImport("shell32")] + [DllImport("shell32", CharSet = CharSet.Unicode)] public static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons); - [DllImport("shell32", CharSet = CharSet.Auto)] + [DllImport("shell32", CharSet = CharSet.Unicode)] internal static extern IntPtr ExtractAssociatedIcon(HandleRef hInst, StringBuilder iconPath, ref int index); /// diff --git a/GreenshotPlugin/UnmanagedHelpers/User32.cs b/GreenshotPlugin/UnmanagedHelpers/User32.cs index 8f42370d1..ac4447ed3 100644 --- a/GreenshotPlugin/UnmanagedHelpers/User32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/User32.cs @@ -60,7 +60,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { [return: MarshalAs(UnmanagedType.Bool)] public extern static bool IsWindowVisible(IntPtr hWnd); [DllImport("user32", SetLastError = true)] - public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out IntPtr processId); + public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); [DllImport("user32", SetLastError = true)] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport("user32", SetLastError = true)] @@ -100,8 +100,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] public extern static int GetClassName (IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32", SetLastError = true)] - public static extern IntPtr GetClassLong(IntPtr hWnd, int nIndex); - [DllImport("user32", SetLastError = true)] + public static extern uint GetClassLong(IntPtr hWnd, int nIndex); + [DllImport("user32", SetLastError = true, EntryPoint = "GetClassLongPtr")] public static extern IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex); [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] @@ -110,14 +110,14 @@ namespace GreenshotPlugin.UnmanagedHelpers { public extern static IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32", SetLastError = true)] public extern static IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); + [DllImport("user32", SetLastError = true, EntryPoint = "GetWindowLong")] + public extern static int GetWindowLong(IntPtr hwnd, int index); + [DllImport("user32", SetLastError = true, EntryPoint = "GetWindowLongPtr")] + public extern static IntPtr GetWindowLongPtr(IntPtr hwnd, int nIndex); [DllImport("user32", SetLastError = true)] - public extern static uint GetWindowLong(IntPtr hwnd, int index); + public static extern int SetWindowLong(IntPtr hWnd, int index, int styleFlags); [DllImport("user32", SetLastError = true)] - public extern static uint GetWindowLongPtr(IntPtr hwnd, int nIndex); - [DllImport("user32", SetLastError = true)] - public static extern int SetWindowLong(IntPtr hWnd, int index, uint styleFlags); - [DllImport("user32", SetLastError = true)] - public static extern int SetWindowLongPtr(IntPtr hWnd, int index, uint styleFlags); + public static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int index, IntPtr styleFlags); [DllImport("user32", SetLastError = true)] public static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags); [DllImport("user32", SetLastError = true)] @@ -126,9 +126,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowInfo(IntPtr hwnd, ref WindowInfo pwi); [DllImport("user32", SetLastError = true)] - public extern static int EnumWindows(EnumWindowsProc lpEnumFunc, int lParam); + public extern static int EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); [DllImport("user32", SetLastError = true)] - public extern static int EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, int lParam); + public extern static int EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetScrollInfo(IntPtr hwnd, int fnBar, ref SCROLLINFO lpsi); @@ -151,7 +151,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { public static extern IntPtr GetDC(IntPtr hwnd); [DllImport("user32", SetLastError = true)] - public static extern void ReleaseDC(IntPtr dc); + public static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32", SetLastError = true)] public static extern IntPtr GetClipboardOwner(); @@ -167,9 +167,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { public static extern IntPtr SetWinEventHook(WinEvent eventMin, WinEvent eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, int idProcess, int idThread, WinEventHookFlags dwFlags); // Added for finding Metro apps, Greenshot 1.1 - [DllImport("user32", SetLastError = true)] + [DllImport("user32", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); - [DllImport("user32", SetLastError = true)] + [DllImport("user32", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); /// uiFlags: 0 - Count of GDI objects @@ -181,7 +181,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// [DllImport("user32", SetLastError = true)] public static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags); - [DllImport("user32", EntryPoint = "RegisterWindowMessageA", SetLastError = true)] + [DllImport("user32", EntryPoint = "RegisterWindowMessageA", SetLastError = true, CharSet = CharSet.Unicode)] public static extern uint RegisterWindowMessage(string lpString); [DllImport("user32", SetLastError=true, CharSet=CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out UIntPtr lpdwResult); @@ -223,7 +223,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { if (IntPtr.Size > 4) { return GetClassLongPtr(hWnd, nIndex); } else { - return GetClassLong(hWnd, nIndex); + return new IntPtr(GetClassLong(hWnd, nIndex)); } } @@ -233,9 +233,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// /// - public static uint GetWindowLongWrapper(IntPtr hwnd, int nIndex) { + public static long GetWindowLongWrapper(IntPtr hwnd, int nIndex) { if (IntPtr.Size == 8) { - return GetWindowLongPtr(hwnd, nIndex); + return GetWindowLongPtr(hwnd, nIndex).ToInt64(); } else { return GetWindowLong(hwnd, nIndex); } @@ -247,20 +247,24 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// /// - public static void SetWindowLongWrapper(IntPtr hwnd, int nIndex, uint styleFlags) { + public static void SetWindowLongWrapper(IntPtr hwnd, int nIndex, IntPtr styleFlags) { if (IntPtr.Size == 8) { SetWindowLongPtr(hwnd, nIndex, styleFlags); } else { - SetWindowLong(hwnd, nIndex, styleFlags); + SetWindowLong(hwnd, nIndex, styleFlags.ToInt32()); } } public static uint GetGuiResourcesGDICount() { - return GetGuiResources(Process.GetCurrentProcess().Handle, 0); + using (Process currentProcess = Process.GetCurrentProcess()) { + return GetGuiResources(currentProcess.Handle, 0); + } } public static uint GetGuiResourcesUserCount() { - return GetGuiResources(Process.GetCurrentProcess().Handle, 1); + using (Process currentProcess = Process.GetCurrentProcess()) { + return GetGuiResources(currentProcess.Handle, 1); + } } /// diff --git a/GreenshotPlugin/UnmanagedHelpers/Win32Errors.cs b/GreenshotPlugin/UnmanagedHelpers/Win32Errors.cs index 8aaca7a76..858f01013 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Win32Errors.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Win32Errors.cs @@ -92,7 +92,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } public static class Win32 { - [DllImport("kernel32.dll")] + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, [Out] StringBuilder lpBuffer, int nSize, IntPtr Arguments); [DllImport("kernel32.dll")]