diff --git a/Greenshot/Configuration/EditorConfiguration.cs b/Greenshot/Configuration/EditorConfiguration.cs index 4c805e5ce..3d3240273 100644 --- a/Greenshot/Configuration/EditorConfiguration.cs +++ b/Greenshot/Configuration/EditorConfiguration.cs @@ -73,7 +73,7 @@ namespace Greenshot.Configuration { /// Type of the class for which to create the field /// FieldType of the field to construct - /// FieldType of the field to construct + /// /// a new Field of the given fieldType, with the scope of it's value being restricted to the Type scope public Field CreateField(Type requestingType, FieldType fieldType, object preferredDefaultValue) { string requestingTypeName = requestingType.Name; diff --git a/Greenshot/Controls/BindableToolStripButton.cs b/Greenshot/Controls/BindableToolStripButton.cs index 5641a9c27..a9f41b1a3 100644 --- a/Greenshot/Controls/BindableToolStripButton.cs +++ b/Greenshot/Controls/BindableToolStripButton.cs @@ -36,7 +36,8 @@ namespace Greenshot.Controls { set; } - public BindableToolStripButton() :base() { + public BindableToolStripButton() + { CheckedChanged += BindableToolStripButton_CheckedChanged; } diff --git a/Greenshot/Controls/BindableToolStripComboBox.cs b/Greenshot/Controls/BindableToolStripComboBox.cs index 192e25ecb..f65188a11 100644 --- a/Greenshot/Controls/BindableToolStripComboBox.cs +++ b/Greenshot/Controls/BindableToolStripComboBox.cs @@ -36,7 +36,8 @@ namespace Greenshot.Controls { set; } - public BindableToolStripComboBox() :base() { + public BindableToolStripComboBox() + { SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; } diff --git a/Greenshot/Controls/BindableToolStripDropDownButton.cs b/Greenshot/Controls/BindableToolStripDropDownButton.cs index d32b2453d..57cb593b4 100644 --- a/Greenshot/Controls/BindableToolStripDropDownButton.cs +++ b/Greenshot/Controls/BindableToolStripDropDownButton.cs @@ -38,9 +38,6 @@ namespace Greenshot.Controls { set; } - public BindableToolStripDropDownButton() { - } - public object SelectedTag { get { if(Tag==null && DropDownItems.Count>0) Tag=DropDownItems[0].Tag; return Tag; } set { AdoptFromTag(value); } diff --git a/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs b/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs index 6c18554da..d8c8ef68c 100644 --- a/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs +++ b/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs @@ -30,7 +30,7 @@ namespace Greenshot.Controls { /// ToolStripProfessionalRenderer which draws the Check correctly when the icons are larger /// public class ContextMenuToolStripProfessionalRenderer : ToolStripProfessionalRenderer { - private static CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); + private static readonly CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); private static Image scaledCheckbox; protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { diff --git a/Greenshot/Controls/FontFamilyComboBox.cs b/Greenshot/Controls/FontFamilyComboBox.cs index 410c87402..b832247c4 100644 --- a/Greenshot/Controls/FontFamilyComboBox.cs +++ b/Greenshot/Controls/FontFamilyComboBox.cs @@ -41,12 +41,16 @@ namespace Greenshot.Controls { } } - public FontFamilyComboBox() : base() { - ComboBox.DataSource = FontFamily.Families; - ComboBox.DisplayMember = "Name"; - SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; - ComboBox.DrawMode = DrawMode.OwnerDrawFixed; - ComboBox.DrawItem += ComboBox_DrawItem; + public FontFamilyComboBox() + { + if (ComboBox != null) + { + ComboBox.DataSource = FontFamily.Families; + ComboBox.DisplayMember = "Name"; + SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; + ComboBox.DrawMode = DrawMode.OwnerDrawFixed; + ComboBox.DrawItem += ComboBox_DrawItem; + } } void ComboBox_DrawItem(object sender, DrawItemEventArgs e) { @@ -58,7 +62,7 @@ namespace Greenshot.Controls { if (e.Index > -1) { FontFamily fontFamily = Items[e.Index] as FontFamily; FontStyle fontStyle = FontStyle.Regular; - if (!fontFamily.IsStyleAvailable(FontStyle.Regular)) { + if (fontFamily != null && !fontFamily.IsStyleAvailable(FontStyle.Regular)) { if (fontFamily.IsStyleAvailable(FontStyle.Bold)) { fontStyle = FontStyle.Bold; } else if (fontFamily.IsStyleAvailable(FontStyle.Italic)) { @@ -70,10 +74,16 @@ namespace Greenshot.Controls { } } try { - DrawText(e.Graphics, fontFamily, fontStyle, e.Bounds, fontFamily.Name); + if (fontFamily != null) + { + DrawText(e.Graphics, fontFamily, fontStyle, e.Bounds, fontFamily.Name); + } } catch { // If the drawing failed, BUG-1770 seems to have a weird case that causes: Font 'Lucida Sans Typewriter' does not support style 'Regular' - DrawText(e.Graphics, FontFamily.GenericSansSerif, FontStyle.Regular, e.Bounds, fontFamily.Name); + if (fontFamily != null) + { + DrawText(e.Graphics, FontFamily.GenericSansSerif, FontStyle.Regular, e.Bounds, fontFamily.Name); + } } } // Uncomment this if you actually like the way the focus rectangle looks @@ -89,7 +99,7 @@ namespace Greenshot.Controls { /// /// private void DrawText(Graphics graphics, FontFamily fontFamily, FontStyle fontStyle, Rectangle bounds, string text) { - using (Font font = new Font(fontFamily, this.Font.Size + 5, fontStyle, GraphicsUnit.Pixel)) { + using (Font font = new Font(fontFamily, Font.Size + 5, fontStyle, GraphicsUnit.Pixel)) { // Make sure the text is visible by centering it in the line using (StringFormat stringFormat = new StringFormat()) { stringFormat.LineAlignment = StringAlignment.Center; diff --git a/Greenshot/Controls/MenuStripEx.cs b/Greenshot/Controls/MenuStripEx.cs index aa880f06e..5400260a0 100644 --- a/Greenshot/Controls/MenuStripEx.cs +++ b/Greenshot/Controls/MenuStripEx.cs @@ -32,11 +32,9 @@ namespace Greenshot.Controls { enum NativeConstants : uint { MA_ACTIVATE = 1, MA_ACTIVATEANDEAT = 2, - MA_NOACTIVATE = 3, - MA_NOACTIVATEANDEAT = 4, } - private bool clickThrough = false; + private bool _clickThrough; /// /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// @@ -45,17 +43,17 @@ namespace Greenshot.Controls { /// public bool ClickThrough { get { - return clickThrough; + return _clickThrough; } set { - clickThrough = value; + _clickThrough = value; } } protected override void WndProc(ref Message m) { base.WndProc(ref m); - if (clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) { + if (_clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) { m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; } } diff --git a/Greenshot/Controls/NonJumpingPanel.cs b/Greenshot/Controls/NonJumpingPanel.cs index 8392b9219..93f2f713c 100644 --- a/Greenshot/Controls/NonJumpingPanel.cs +++ b/Greenshot/Controls/NonJumpingPanel.cs @@ -19,14 +19,13 @@ * along with this program. If not, see . */ -/// -/// See: http://nickstips.wordpress.com/2010/03/03/c-panel-resets-scroll-position-after-focus-is-lost-and-regained/ -/// - using System.Drawing; using System.Windows.Forms; namespace GreenshotPlugin.Controls { + /// + /// See: http://nickstips.wordpress.com/2010/03/03/c-panel-resets-scroll-position-after-focus-is-lost-and-regained/ + /// public class NonJumpingPanel : Panel { protected override Point ScrollToControl(Control activeControl) { // Returning the current location prevents the panel from diff --git a/Greenshot/Controls/Pipette.cs b/Greenshot/Controls/Pipette.cs index 6aeccf9b5..5a730c4b4 100644 --- a/Greenshot/Controls/Pipette.cs +++ b/Greenshot/Controls/Pipette.cs @@ -34,7 +34,7 @@ namespace Greenshot.Controls { private MovableShowColorForm movableShowColorForm; private bool dragging; private Cursor _cursor; - private Bitmap _image; + private readonly Bitmap _image; private const int VK_ESC = 27; public event EventHandler PipetteUsed; @@ -111,10 +111,14 @@ namespace Greenshot.Controls { /// /// MouseEventArgs protected override void OnMouseUp(MouseEventArgs e) { - if (e.Button == MouseButtons.Left) { + if (e.Button == MouseButtons.Left) + { //Release Capture should consume MouseUp when canceled with the escape key User32.ReleaseCapture(); - PipetteUsed(this, new PipetteUsedArgs(movableShowColorForm.color)); + if (PipetteUsed != null) + { + PipetteUsed(this, new PipetteUsedArgs(movableShowColorForm.color)); + } } base.OnMouseUp(e); } diff --git a/Greenshot/Controls/ToolStripEx.cs b/Greenshot/Controls/ToolStripEx.cs index 3a32224c3..2ce378d3f 100644 --- a/Greenshot/Controls/ToolStripEx.cs +++ b/Greenshot/Controls/ToolStripEx.cs @@ -32,11 +32,9 @@ namespace Greenshot.Controls { enum NativeConstants : uint { MA_ACTIVATE = 1, MA_ACTIVATEANDEAT = 2, - MA_NOACTIVATE = 3, - MA_NOACTIVATEANDEAT = 4, } - private bool clickThrough = false; + private bool _clickThrough; /// /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// @@ -46,17 +44,17 @@ namespace Greenshot.Controls { public bool ClickThrough { get { - return clickThrough; + return _clickThrough; } set { - clickThrough = value; + _clickThrough = value; } } protected override void WndProc(ref Message m) { base.WndProc(ref m); - if (clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) { + if (_clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) { m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; } } diff --git a/Greenshot/Destinations/ClipboardDestination.cs b/Greenshot/Destinations/ClipboardDestination.cs index 25476f64e..5638b7fd1 100644 --- a/Greenshot/Destinations/ClipboardDestination.cs +++ b/Greenshot/Destinations/ClipboardDestination.cs @@ -25,16 +25,12 @@ using System.Windows.Forms; using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; -using Greenshot.IniFile; -using log4net; namespace Greenshot.Destinations { /// /// Description of ClipboardDestination. /// public class ClipboardDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(ClipboardDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "Clipboard"; public override string Designation { diff --git a/Greenshot/Destinations/EditorDestination.cs b/Greenshot/Destinations/EditorDestination.cs index 0aaed76a2..2f5234705 100644 --- a/Greenshot/Destinations/EditorDestination.cs +++ b/Greenshot/Destinations/EditorDestination.cs @@ -32,11 +32,11 @@ namespace Greenshot.Destinations { /// Description of EditorDestination. /// public class EditorDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(EditorDestination)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(EditorDestination)); + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); public const string DESIGNATION = "Editor"; - private IImageEditor editor = null; - private static Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap(); + private readonly IImageEditor editor; + private static readonly Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap(); public EditorDestination() { } @@ -79,8 +79,8 @@ namespace Greenshot.Destinations { } public override IEnumerable DynamicDestinations() { - foreach (IImageEditor editor in ImageEditorForm.Editors) { - yield return new EditorDestination(editor); + foreach (IImageEditor someEditor in ImageEditorForm.Editors) { + yield return new EditorDestination(someEditor); } } diff --git a/Greenshot/Destinations/EmailDestination.cs b/Greenshot/Destinations/EmailDestination.cs index b82b233b0..16dcf0866 100644 --- a/Greenshot/Destinations/EmailDestination.cs +++ b/Greenshot/Destinations/EmailDestination.cs @@ -36,9 +36,9 @@ namespace Greenshot.Destinations { public class EmailDestination : AbstractDestination { private static ILog LOG = LogManager.GetLogger(typeof(EmailDestination)); private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static Image mailIcon = GreenshotResources.getImage("Email.Image"); - private static bool isActiveFlag = false; - private static string mapiClient = null; + private static readonly Image mailIcon = GreenshotResources.getImage("Email.Image"); + private static bool isActiveFlag; + private static string mapiClient; public const string DESIGNATION = "EMail"; static EmailDestination() { diff --git a/Greenshot/Destinations/FileDestination.cs b/Greenshot/Destinations/FileDestination.cs index 24af9bd1d..6b2c0b24d 100644 --- a/Greenshot/Destinations/FileDestination.cs +++ b/Greenshot/Destinations/FileDestination.cs @@ -35,8 +35,8 @@ namespace Greenshot.Destinations { /// Description of FileSaveAsDestination. /// public class FileDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(FileDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(FileDestination)); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "FileNoDialog"; public override string Designation { @@ -103,20 +103,23 @@ namespace Greenshot.Destinations { LOG.InfoFormat("Not overwriting: {0}", ex1.Message); // when we don't allow to overwrite present a new SaveWithDialog fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); - outputMade = (fullPath != null); + outputMade = fullPath != null; } catch (Exception ex2) { LOG.Error("Error saving screenshot!", ex2); // Show the problem MessageBox.Show(Language.GetString(LangKey.error_save), Language.GetString(LangKey.error)); // when save failed we present a SaveWithDialog fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); - outputMade = (fullPath != null); + outputMade = fullPath != null; } // Don't overwrite filename if no output is made if (outputMade) { exportInformation.ExportMade = outputMade; exportInformation.Filepath = fullPath; - captureDetails.Filename = fullPath; + if (captureDetails != null) + { + captureDetails.Filename = fullPath; + } conf.OutputFileAsFullpath = fullPath; } diff --git a/Greenshot/Destinations/FileWithDialogDestination.cs b/Greenshot/Destinations/FileWithDialogDestination.cs index e14b804b6..d5e76ebfb 100644 --- a/Greenshot/Destinations/FileWithDialogDestination.cs +++ b/Greenshot/Destinations/FileWithDialogDestination.cs @@ -34,7 +34,7 @@ namespace Greenshot.Destinations { /// public class FileWithDialogDestination : AbstractDestination { private static ILog LOG = LogManager.GetLogger(typeof(FileWithDialogDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "FileDialog"; public override string Designation { diff --git a/Greenshot/Destinations/PrinterDestination.cs b/Greenshot/Destinations/PrinterDestination.cs index bc4ce8af0..ec37b8bcf 100644 --- a/Greenshot/Destinations/PrinterDestination.cs +++ b/Greenshot/Destinations/PrinterDestination.cs @@ -28,18 +28,14 @@ using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; using Greenshot.Helpers; -using Greenshot.IniFile; -using log4net; namespace Greenshot.Destinations { /// /// Description of PrinterDestination. /// public class PrinterDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(PrinterDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "Printer"; - public string printerName = null; + public string printerName; public PrinterDestination() { } diff --git a/Greenshot/Drawing/ArrowContainer.cs b/Greenshot/Drawing/ArrowContainer.cs index f1c65ff53..57c2fe8c1 100644 --- a/Greenshot/Drawing/ArrowContainer.cs +++ b/Greenshot/Drawing/ArrowContainer.cs @@ -79,7 +79,7 @@ namespace Greenshot.Drawing { Top + currentStep + Height); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } diff --git a/Greenshot/Drawing/CursorContainer.cs b/Greenshot/Drawing/CursorContainer.cs index 3911d5940..2b5969c92 100644 --- a/Greenshot/Drawing/CursorContainer.cs +++ b/Greenshot/Drawing/CursorContainer.cs @@ -33,7 +33,7 @@ namespace Greenshot.Drawing { /// [Serializable] public class CursorContainer : DrawableContainer, ICursorContainer { - private static ILog LOG = LogManager.GetLogger(typeof(CursorContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(CursorContainer)); protected Cursor cursor; diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index aa4ffce43..9b3a10952 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -46,10 +46,8 @@ namespace Greenshot.Drawing { public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDrawableContainer { private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer)); protected static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection(); - private bool isMadeUndoable; + private bool _isMadeUndoable; private const int M11 = 0; - private const int M12 = 1; - private const int M21 = 2; private const int M22 = 3; @@ -305,7 +303,7 @@ namespace Greenshot.Drawing { Left = _parent.Width - Width - lineThickness/2; } if (horizontalAlignment == HorizontalAlignment.Center) { - Left = (_parent.Width / 2) - (Width / 2) - lineThickness/2; + Left = _parent.Width / 2 - Width / 2 - lineThickness/2; } if (verticalAlignment == VerticalAlignment.TOP) { @@ -315,7 +313,7 @@ namespace Greenshot.Drawing { Top = _parent.Height - Height - lineThickness/2; } if (verticalAlignment == VerticalAlignment.CENTER) { - Top = (_parent.Height / 2) - (Height / 2) - lineThickness/2; + Top = _parent.Height / 2 - Height / 2 - lineThickness/2; } } @@ -455,7 +453,7 @@ namespace Greenshot.Drawing { } else { Status = EditStatus.MOVING; } - isMadeUndoable = false; + _isMadeUndoable = false; } private void GripperMouseUp(object sender, MouseEventArgs e) { @@ -463,7 +461,7 @@ namespace Greenshot.Drawing { if (originatingGripper != _targetGripper) { _boundsBeforeResize = Rectangle.Empty; _boundsAfterResize = RectangleF.Empty; - isMadeUndoable = false; + _isMadeUndoable = false; } Status = EditStatus.IDLE; Invalidate(); @@ -478,9 +476,9 @@ namespace Greenshot.Drawing { TargetGripperMove(absX, absY); } else if (Status.Equals(EditStatus.RESIZING)) { // check if we already made this undoable - if (!isMadeUndoable) { + if (!_isMadeUndoable) { // don't allow another undo until we are finished with this move - isMadeUndoable = true; + _isMadeUndoable = true; // Make undo-able MakeBoundsChangeUndoable(false); } @@ -699,6 +697,8 @@ namespace Greenshot.Drawing { } public override int GetHashCode() { + // TODO: This actually doesn't make sense... + // Place the container in a list, and you can't find it :) return left.GetHashCode() ^ top.GetHashCode() ^ width.GetHashCode() ^ height.GetHashCode() ^ GetFields().GetHashCode(); } diff --git a/Greenshot/Drawing/DrawableContainerList.cs b/Greenshot/Drawing/DrawableContainerList.cs index 570949a40..46daf9773 100644 --- a/Greenshot/Drawing/DrawableContainerList.cs +++ b/Greenshot/Drawing/DrawableContainerList.cs @@ -322,7 +322,7 @@ namespace Greenshot.Drawing { if (!elements.Contains(dc)) { continue; } - if (Count > (i+1) && !elements.Contains(this[i+1])) { + if (Count > i+1 && !elements.Contains(this[i+1])) { SwapElements(i,i+1); } } @@ -468,7 +468,7 @@ namespace Greenshot.Drawing { // Copy item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)); - item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); + item.Image = (Image)editorFormResources.GetObject("copyToolStripMenuItem.Image"); item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); }; @@ -476,7 +476,7 @@ namespace Greenshot.Drawing { // Cut item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)); - item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image"))); + item.Image = (Image)editorFormResources.GetObject("btnCut.Image"); item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); List containersToDelete = new List(); @@ -492,7 +492,7 @@ namespace Greenshot.Drawing { // Delete item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement)); - item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); + item.Image = (Image)editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"); item.Click += delegate { List containersToDelete = new List(); foreach(var drawableContainer in this) { diff --git a/Greenshot/Drawing/EllipseContainer.cs b/Greenshot/Drawing/EllipseContainer.cs index caf41824b..c4fe278e1 100644 --- a/Greenshot/Drawing/EllipseContainer.cs +++ b/Greenshot/Drawing/EllipseContainer.cs @@ -59,12 +59,15 @@ namespace Greenshot.Drawing { /// /// This allows another container to draw an ellipse /// - /// + /// /// /// + /// + /// + /// + /// public static void DrawEllipse(Rectangle rect, Graphics graphics, RenderMode renderMode, int lineThickness, Color lineColor, Color fillColor, bool shadow) { - - bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); + bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor); // draw shadow before anything else if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { int basealpha = 100; diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs index 0f8df4937..4bb0316fb 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs @@ -34,7 +34,7 @@ namespace Greenshot.Drawing.Fields { [Serializable] public abstract class AbstractFieldHolder : IFieldHolder { private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); /// /// called when a field's value has changed @@ -50,10 +50,8 @@ namespace Greenshot.Drawing.Fields { // this allows us to use default serialization [NonSerialized] private Dictionary fieldsByType = new Dictionary(); - private List fields = new List(); - - public AbstractFieldHolder() {} - + private readonly List fields = new List(); + [OnDeserialized] private void OnDeserialized(StreamingContext context) { fieldsByType = new Dictionary(); diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs index b919edd9b..3114ffc46 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -30,8 +30,7 @@ namespace Greenshot.Drawing.Fields { /// [Serializable()] public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder { - - FieldChangedEventHandler fieldChangedEventHandler; + readonly FieldChangedEventHandler fieldChangedEventHandler; [NonSerialized] private EventHandler childrenChanged; diff --git a/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs b/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs index da43dd6f3..5c31e0286 100644 --- a/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs +++ b/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs @@ -26,8 +26,6 @@ namespace Greenshot.Drawing.Fields.Binding { /// public abstract class AbstractBindingConverter : IBindingConverter { - public AbstractBindingConverter() {} - public object convert(object o) { if(o == null) { return null; diff --git a/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs b/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs index 21ebeb1ef..ca109731a 100644 --- a/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs +++ b/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs @@ -29,35 +29,35 @@ namespace Greenshot.Drawing.Fields.Binding { /// behavior (e.g. when binding to a /// public class BidirectionalBinding { - private INotifyPropertyChanged controlObject; - private INotifyPropertyChanged fieldObject; - private string controlPropertyName; - private string fieldPropertyName; - private bool updatingControl = false; - private bool updatingField = false; - private IBindingConverter converter; - private IBindingValidator validator; + private readonly INotifyPropertyChanged _controlObject; + private readonly INotifyPropertyChanged _fieldObject; + private readonly string _controlPropertyName; + private readonly string _fieldPropertyName; + private bool _updatingControl; + private bool _updatingField; + private IBindingConverter _converter; + private readonly IBindingValidator _validator; /// /// Whether or not null values are passed on to the other object. /// protected bool AllowSynchronizeNull = true; - + /// /// Bind properties of two objects bidirectionally /// - /// Object containing 1st property to bind - /// Property of 1st object to bind - /// Object containing 2nd property to bind - /// Property of 2nd object to bind + /// Object containing 1st property to bind + /// Property of 1st object to bind + /// Object containing 2nd property to bind + /// Property of 2nd object to bind public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName) { - this.controlObject = controlObject; - this.fieldObject = fieldObject; - this.controlPropertyName = controlPropertyName; - this.fieldPropertyName = fieldPropertyName; + _controlObject = controlObject; + _fieldObject = fieldObject; + _controlPropertyName = controlPropertyName; + _fieldPropertyName = fieldPropertyName; - this.controlObject.PropertyChanged += ControlPropertyChanged; - this.fieldObject.PropertyChanged += FieldPropertyChanged; + _controlObject.PropertyChanged += ControlPropertyChanged; + _fieldObject.PropertyChanged += FieldPropertyChanged; } /// @@ -69,7 +69,7 @@ namespace Greenshot.Drawing.Fields.Binding { /// Property of 2nd object to bind /// taking care of converting the synchronized value to the correct target format and back public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { - this.converter = converter; + _converter = converter; } /// @@ -82,7 +82,7 @@ namespace Greenshot.Drawing.Fields.Binding { /// Property of 2nd object to bind /// validator to intercept synchronization if the value does not match certain criteria public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { - this.validator = validator; + _validator = validator; } /// @@ -96,46 +96,46 @@ namespace Greenshot.Drawing.Fields.Binding { /// taking care of converting the synchronized value to the correct target format and back /// validator to intercept synchronization if the value does not match certain criteria public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) { - this.validator = validator; + _validator = validator; } public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e) { - if (!updatingControl && e.PropertyName.Equals(controlPropertyName)) { - updatingField = true; - synchronize(controlObject, controlPropertyName, fieldObject, fieldPropertyName); - updatingField = false; + if (!_updatingControl && e.PropertyName.Equals(_controlPropertyName)) { + _updatingField = true; + Synchronize(_controlObject, _controlPropertyName, _fieldObject, _fieldPropertyName); + _updatingField = false; } } public void FieldPropertyChanged(object sender, PropertyChangedEventArgs e) { - if (!updatingField && e.PropertyName.Equals(fieldPropertyName)) { - updatingControl = true; - synchronize(fieldObject, fieldPropertyName, controlObject, controlPropertyName); - updatingControl = false; + if (!_updatingField && e.PropertyName.Equals(_fieldPropertyName)) { + _updatingControl = true; + Synchronize(_fieldObject, _fieldPropertyName, _controlObject, _controlPropertyName); + _updatingControl = false; } } - private void synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) { - PropertyInfo targetPropertyInfo = resolvePropertyInfo(targetObject, targetProperty); - PropertyInfo sourcePropertyInfo = resolvePropertyInfo(sourceObject, sourceProperty); + private void Synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) { + PropertyInfo targetPropertyInfo = ResolvePropertyInfo(targetObject, targetProperty); + PropertyInfo sourcePropertyInfo = ResolvePropertyInfo(sourceObject, sourceProperty); if (sourcePropertyInfo != null && targetPropertyInfo != null && targetPropertyInfo.CanWrite) { object bValue = sourcePropertyInfo.GetValue(sourceObject, null); - if (converter != null && bValue != null) { - bValue = converter.convert(bValue); + if (_converter != null && bValue != null) { + bValue = _converter.convert(bValue); } try { - if (validator == null || validator.validate(bValue)) { + if (_validator == null || _validator.validate(bValue)) { targetPropertyInfo.SetValue(targetObject, bValue, null); } } catch (Exception e) { - throw new MemberAccessException("Could not set property '"+targetProperty+"' to '"+bValue+"' ["+((bValue!=null)?bValue.GetType().Name:"")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e); + throw new MemberAccessException("Could not set property '"+targetProperty+"' to '"+bValue+"' ["+(bValue!=null?bValue.GetType().Name:"")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e); } } } - private PropertyInfo resolvePropertyInfo(object obj, string property) { + private static PropertyInfo ResolvePropertyInfo(object obj, string property) { PropertyInfo ret = null; string[] properties = property.Split(".".ToCharArray()); for(int i=0; i @@ -41,13 +40,10 @@ namespace Greenshot.Drawing.Fields { /// public class FieldAggregator : AbstractFieldHolder { - private List boundContainers; - private bool internalUpdateRunning = false; - - enum Status {IDLE, BINDING, UPDATING}; - - private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private readonly List boundContainers; + private bool internalUpdateRunning; + + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); public FieldAggregator() { foreach(FieldType fieldType in FieldType.Values) { diff --git a/Greenshot/Drawing/FilterContainer.cs b/Greenshot/Drawing/FilterContainer.cs index 630c5c35d..7e6b2336e 100644 --- a/Greenshot/Drawing/FilterContainer.cs +++ b/Greenshot/Drawing/FilterContainer.cs @@ -52,7 +52,7 @@ namespace Greenshot.Drawing { int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); bool shadow = GetFieldValueAsBool(FieldType.SHADOW); - bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); + bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor); if (lineVisible) { graphics.SmoothingMode = SmoothingMode.HighSpeed; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; @@ -69,7 +69,7 @@ namespace Greenshot.Drawing { Rectangle shadowRect = GuiRectangle.GetGuiRectangle(Left + currentStep, Top + currentStep, Width, Height); graphics.DrawRectangle(shadowPen, shadowRect); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot/Drawing/Filters/AbstractFilter.cs b/Greenshot/Drawing/Filters/AbstractFilter.cs index cd1be85a2..e34f61008 100644 --- a/Greenshot/Drawing/Filters/AbstractFilter.cs +++ b/Greenshot/Drawing/Filters/AbstractFilter.cs @@ -41,7 +41,7 @@ namespace Greenshot.Drawing.Filters { remove{ propertyChanged -= value; } } - private bool invert = false; + private bool invert; public bool Invert { get { return invert; diff --git a/Greenshot/Drawing/Filters/BlurFilter.cs b/Greenshot/Drawing/Filters/BlurFilter.cs index 1b2e6ab68..1b9ddf5a0 100644 --- a/Greenshot/Drawing/Filters/BlurFilter.cs +++ b/Greenshot/Drawing/Filters/BlurFilter.cs @@ -18,6 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + using System; using System.Drawing; using Greenshot.Drawing.Fields; @@ -25,13 +26,10 @@ using Greenshot.Plugin.Drawing; using GreenshotPlugin.Core; using GreenshotPlugin.UnmanagedHelpers; using System.Drawing.Drawing2D; -using log4net; namespace Greenshot.Drawing.Filters { [Serializable()] public class BlurFilter : AbstractFilter { - private static ILog LOG = LogManager.GetLogger(typeof(BlurFilter)); - public double previewQuality; public double PreviewQuality { get { return previewQuality; } @@ -43,7 +41,7 @@ namespace Greenshot.Drawing.Filters { AddField(GetType(), FieldType.PREVIEW_QUALITY, 1.0d); } - public unsafe override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) { + public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) { int blurRadius = GetFieldValueAsInt(FieldType.BLUR_RADIUS); Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); if (applyRect.Width == 0 || applyRect.Height == 0) { @@ -54,7 +52,7 @@ namespace Greenshot.Drawing.Filters { graphics.SetClip(applyRect); graphics.ExcludeClip(rect); } - if (GDIplus.isBlurPossible(blurRadius)) { + if (GDIplus.IsBlurPossible(blurRadius)) { GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false); } else { using (IFastBitmap fastBitmap = FastBitmap.CreateCloneOf(applyBitmap, applyRect)) { @@ -63,7 +61,6 @@ namespace Greenshot.Drawing.Filters { } } graphics.Restore(state); - return; } } } diff --git a/Greenshot/Drawing/Filters/MagnifierFilter.cs b/Greenshot/Drawing/Filters/MagnifierFilter.cs index 23359546e..c9944b7c3 100644 --- a/Greenshot/Drawing/Filters/MagnifierFilter.cs +++ b/Greenshot/Drawing/Filters/MagnifierFilter.cs @@ -53,7 +53,7 @@ namespace Greenshot.Drawing.Filters { int halfHeight = rect.Height / 2; int newWidth = rect.Width / magnificationFactor; int newHeight = rect.Height / magnificationFactor; - Rectangle source = new Rectangle(rect.X + halfWidth - (newWidth / 2), rect.Y + halfHeight - (newHeight / 2), newWidth, newHeight); + Rectangle source = new Rectangle(rect.X + halfWidth - newWidth / 2, rect.Y + halfHeight - newHeight / 2, newWidth, newHeight); graphics.DrawImage(applyBitmap, rect, source, GraphicsUnit.Pixel); graphics.Restore(state); } diff --git a/Greenshot/Drawing/Filters/PixelizationFilter.cs b/Greenshot/Drawing/Filters/PixelizationFilter.cs index a7f13c096..78e49253f 100644 --- a/Greenshot/Drawing/Filters/PixelizationFilter.cs +++ b/Greenshot/Drawing/Filters/PixelizationFilter.cs @@ -37,7 +37,7 @@ namespace Greenshot.Drawing.Filters { public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) { int pixelSize = GetFieldValueAsInt(FieldType.PIXEL_SIZE); - Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); + ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); if (pixelSize <= 1 || rect.Width == 0 || rect.Height == 0) { // Nothing to do return; diff --git a/Greenshot/Drawing/FreehandContainer.cs b/Greenshot/Drawing/FreehandContainer.cs index b30937c2b..5294f5bd5 100644 --- a/Greenshot/Drawing/FreehandContainer.cs +++ b/Greenshot/Drawing/FreehandContainer.cs @@ -22,7 +22,6 @@ using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; -using log4net; using System; using System.Collections.Generic; using System.Drawing; @@ -35,15 +34,14 @@ namespace Greenshot.Drawing { /// [Serializable] public class FreehandContainer : DrawableContainer { - private static readonly ILog LOG = LogManager.GetLogger(typeof(FreehandContainer)); private static readonly float [] POINT_OFFSET = new float[]{0.5f, 0.25f, 0.75f}; [NonSerialized] private GraphicsPath freehandPath = new GraphicsPath(); private Rectangle myBounds = Rectangle.Empty; private Point lastMouse = Point.Empty; - private List capturePoints = new List(); - private bool isRecalculated = false; + private readonly List capturePoints = new List(); + private bool isRecalculated; /// /// Constructor @@ -119,7 +117,7 @@ namespace Greenshot.Drawing { public override bool HandleMouseMove(int mouseX, int mouseY) { Point previousPoint = capturePoints[capturePoints.Count-1]; - if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= (2*EditorConfig.FreehandSensitivity)) { + if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= 2*EditorConfig.FreehandSensitivity) { capturePoints.Add(new Point(mouseX, mouseY)); } if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) { @@ -232,7 +230,7 @@ namespace Greenshot.Drawing { if (!myBounds.IsEmpty) { int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS)); int safetymargin = 10; - return new Rectangle((myBounds.Left + Left) - (safetymargin+lineThickness), (myBounds.Top + Top) - (safetymargin+lineThickness), myBounds.Width + (2*(lineThickness+safetymargin)), myBounds.Height + (2*(lineThickness+safetymargin))); + return new Rectangle(myBounds.Left + Left - (safetymargin+lineThickness), myBounds.Top + Top - (safetymargin+lineThickness), myBounds.Width + 2*(lineThickness+safetymargin), myBounds.Height + 2*(lineThickness+safetymargin)); } return new Rectangle(0, 0, _parent.Width, _parent.Height); } diff --git a/Greenshot/Drawing/IconContainer.cs b/Greenshot/Drawing/IconContainer.cs index 86b82a46f..846ee3cde 100644 --- a/Greenshot/Drawing/IconContainer.cs +++ b/Greenshot/Drawing/IconContainer.cs @@ -31,7 +31,7 @@ namespace Greenshot.Drawing { /// [Serializable] public class IconContainer : DrawableContainer, IIconContainer { - private static ILog LOG = LogManager.GetLogger(typeof(IconContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(IconContainer)); protected Icon icon; diff --git a/Greenshot/Drawing/ImageContainer.cs b/Greenshot/Drawing/ImageContainer.cs index b9f9c6dc3..25894af74 100644 --- a/Greenshot/Drawing/ImageContainer.cs +++ b/Greenshot/Drawing/ImageContainer.cs @@ -34,7 +34,7 @@ namespace Greenshot.Drawing { /// [Serializable] public class ImageContainer : DrawableContainer, IImageContainer { - private static ILog LOG = LogManager.GetLogger(typeof(ImageContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageContainer)); private Image image; diff --git a/Greenshot/Drawing/LineContainer.cs b/Greenshot/Drawing/LineContainer.cs index 4189134ac..b11486901 100644 --- a/Greenshot/Drawing/LineContainer.cs +++ b/Greenshot/Drawing/LineContainer.cs @@ -86,7 +86,7 @@ namespace Greenshot.Drawing { Top + currentStep + Height); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot/Drawing/RectangleContainer.cs b/Greenshot/Drawing/RectangleContainer.cs index c235346c5..933adb180 100644 --- a/Greenshot/Drawing/RectangleContainer.cs +++ b/Greenshot/Drawing/RectangleContainer.cs @@ -69,7 +69,7 @@ namespace Greenshot.Drawing { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.None; - bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); + bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor); if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { //draw shadow first int basealpha = 100; @@ -86,7 +86,7 @@ namespace Greenshot.Drawing { rect.Height); graphics.DrawRectangle(shadowPen, shadowRect); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot/Drawing/RoundedRectangle.cs b/Greenshot/Drawing/RoundedRectangle.cs index 51ea777ff..1eaa7485f 100644 --- a/Greenshot/Drawing/RoundedRectangle.cs +++ b/Greenshot/Drawing/RoundedRectangle.cs @@ -35,13 +35,13 @@ namespace Greenshot.Drawing { public static GraphicsPath Create2(int x, int y, int width, int height, int radius) { GraphicsPath gp = new GraphicsPath(); - gp.AddLine(x + radius, y, x + width - (radius * 2), y); // Line - gp.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90); // Corner - gp.AddLine(x + width, y + radius, x + width, y + height - (radius * 2)); // Line - gp.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90); // Corner - gp.AddLine(x + width - (radius * 2), y + height, x + radius, y + height); // Line - gp.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90); // Corner - gp.AddLine(x, y + height - (radius * 2), x, y + radius); // Line + gp.AddLine(x + radius, y, x + width - radius * 2, y); // Line + gp.AddArc(x + width - radius * 2, y, radius * 2, radius * 2, 270, 90); // Corner + gp.AddLine(x + width, y + radius, x + width, y + height - radius * 2); // Line + gp.AddArc(x + width - radius * 2, y + height - radius * 2, radius * 2, radius * 2, 0, 90); // Corner + gp.AddLine(x + width - radius * 2, y + height, x + radius, y + height); // Line + gp.AddArc(x, y + height - radius * 2, radius * 2, radius * 2, 90, 90); // Corner + gp.AddLine(x, y + height - radius * 2, x, y + radius); // Line gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner gp.CloseFigure(); diff --git a/Greenshot/Drawing/SpeechbubbleContainer.cs b/Greenshot/Drawing/SpeechbubbleContainer.cs index 64ede51e8..eef5e8ef6 100644 --- a/Greenshot/Drawing/SpeechbubbleContainer.cs +++ b/Greenshot/Drawing/SpeechbubbleContainer.cs @@ -180,7 +180,7 @@ namespace Greenshot.Drawing { private GraphicsPath CreateTail() { Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); - int tailLength = GeometryHelper.Distance2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Left, TargetGripper.Top); + int tailLength = GeometryHelper.Distance2D(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, TargetGripper.Left, TargetGripper.Top); int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20; // This should fix a problem with the tail being to wide @@ -192,10 +192,10 @@ namespace Greenshot.Drawing { tail.AddLine(tailWidth, 0, 0, -tailLength); tail.CloseFigure(); - int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Left, TargetGripper.Top); + int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, TargetGripper.Left, TargetGripper.Top); using (Matrix tailMatrix = new Matrix()) { - tailMatrix.Translate(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2)); + tailMatrix.Translate(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2); tailMatrix.Rotate(tailAngle); tail.Transform(tailMatrix); } @@ -223,7 +223,7 @@ namespace Greenshot.Drawing { bool shadow = GetFieldValueAsBool(FieldType.SHADOW); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); - bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); + bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor); Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); if (Selected && renderMode == RenderMode.EDIT) { @@ -253,7 +253,7 @@ namespace Greenshot.Drawing { graphics.DrawPath(shadowPen, bubbleClone); } currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot/Drawing/StepLabelContainer.cs b/Greenshot/Drawing/StepLabelContainer.cs index 79583c5ab..e42076c82 100644 --- a/Greenshot/Drawing/StepLabelContainer.cs +++ b/Greenshot/Drawing/StepLabelContainer.cs @@ -118,7 +118,7 @@ namespace Greenshot.Drawing { /// This makes it possible for the label to be placed exactly in the middle of the pointer. /// public override bool HandleMouseDown(int mouseX, int mouseY) { - return base.HandleMouseDown(mouseX - (Width / 2), mouseY - (Height / 2)); + return base.HandleMouseDown(mouseX - Width / 2, mouseY - Height / 2); } /// @@ -146,8 +146,8 @@ namespace Greenshot.Drawing { public override bool HandleMouseMove(int x, int y) { Invalidate(); - Left = x - (Width / 2); - Top = y - (Height / 2); + Left = x - Width / 2; + Top = y - Height / 2; Invalidate(); return true; } @@ -167,7 +167,7 @@ namespace Greenshot.Drawing { int widthAfter = rect.Width; int heightAfter = rect.Height; - float factor = (((float)widthAfter / widthBefore) + ((float)heightAfter / heightBefore)) / 2; + float factor = ((float)widthAfter / widthBefore + (float)heightAfter / heightBefore) / 2; fontSize *= factor; } diff --git a/Greenshot/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index b28e2a86f..22c1aea93 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -46,9 +46,9 @@ namespace Greenshot.Drawing { /// Description of Surface. /// public class Surface : Control, ISurface { - private static ILog LOG = LogManager.GetLogger(typeof(Surface)); - public static int Count = 0; - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(Surface)); + public static int Count; + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); // Property to identify the Surface ID private Guid _uniqueId = Guid.NewGuid(); @@ -169,7 +169,7 @@ namespace Greenshot.Drawing { /// all selected elements, do not serialize /// [NonSerialized] - private DrawableContainerList selectedElements; + private readonly DrawableContainerList selectedElements; /// /// the element we are drawing with, do not serialize @@ -208,7 +208,7 @@ namespace Greenshot.Drawing { /// /// all stepLabels for the surface, needed with serialization /// - private List _stepLabels = new List(); + private readonly List _stepLabels = new List(); public void AddStepLabel(StepLabelContainer stepLabel) { _stepLabels.Add(stepLabel); @@ -225,7 +225,7 @@ namespace Greenshot.Drawing { public int CountStepLabels(IDrawableContainer stopAtContainer) { int number = 1; foreach (var possibleThis in _stepLabels) { - if (possibleThis == stopAtContainer) { + if (possibleThis.Equals(stopAtContainer)) { break; } if (IsOnSurface(possibleThis)) { @@ -1037,7 +1037,10 @@ namespace Greenshot.Drawing { _drawingElement = _undrawnElement; // if a new element has been drawn, set location and register it if (_drawingElement != null) { - _drawingElement.Status = _undrawnElement.DefaultEditMode; + if (_undrawnElement != null) + { + _drawingElement.Status = _undrawnElement.DefaultEditMode; + } _drawingElement.PropertyChanged += ElementPropertyChanged; if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) { _drawingElement.Left = _mouseStart.X; @@ -1331,7 +1334,7 @@ namespace Greenshot.Drawing { /// public bool HasSelectedElements { get { - return (selectedElements != null && selectedElements.Count > 0); + return selectedElements != null && selectedElements.Count > 0; } } @@ -1387,6 +1390,10 @@ namespace Greenshot.Drawing { public void ConfirmSelectedConfirmableElements(bool confirm){ // create new collection so that we can iterate safely (selectedElements might change due with confirm/cancel) List selectedDCs = new List(selectedElements); + if (_cropContainer == null) + { + return; + } foreach (IDrawableContainer dc in selectedDCs){ if (dc.Equals(_cropContainer)){ DrawingMode = DrawingModes.None; @@ -1397,6 +1404,7 @@ namespace Greenshot.Drawing { } _cropContainer.Dispose(); _cropContainer = null; + break; } } } @@ -1423,7 +1431,7 @@ namespace Greenshot.Drawing { if (dcs != null) { // Make element(s) only move 10,10 if the surface is the same Point moveOffset; - bool isSameSurface = (dcs.ParentID == _uniqueId); + bool isSameSurface = dcs.ParentID == _uniqueId; dcs.Parent = this; if (isSameSurface) { moveOffset = new Point(10, 10); diff --git a/Greenshot/Drawing/TextContainer.cs b/Greenshot/Drawing/TextContainer.cs index 110c40775..f02ecbf39 100644 --- a/Greenshot/Drawing/TextContainer.cs +++ b/Greenshot/Drawing/TextContainer.cs @@ -332,8 +332,8 @@ namespace Greenshot.Drawing { if (lineThickness <= 1) { lineWidth = 0; } - _textBox.Width = absRectangle.Width - (2 * lineWidth) + correction; - _textBox.Height = absRectangle.Height - (2 * lineWidth) + correction; + _textBox.Width = absRectangle.Width - 2 * lineWidth + correction; + _textBox.Height = absRectangle.Height - 2 * lineWidth + correction; } public override void ApplyBounds(RectangleF newBounds) { @@ -415,7 +415,7 @@ namespace Greenshot.Drawing { /// /// public static void DrawText(Graphics graphics, Rectangle drawingRectange, int lineThickness, Color fontColor, bool drawShadow, StringFormat stringFormat, string text, Font font) { - int textOffset = (lineThickness > 0) ? (int)Math.Ceiling(lineThickness / 2d) : 0; + int textOffset = lineThickness > 0 ? (int)Math.Ceiling(lineThickness / 2d) : 0; // draw shadow before anything else if (drawShadow) { int basealpha = 100; diff --git a/Greenshot/Forms/AboutForm.cs b/Greenshot/Forms/AboutForm.cs index 64934dea0..f330dcfd6 100644 --- a/Greenshot/Forms/AboutForm.cs +++ b/Greenshot/Forms/AboutForm.cs @@ -41,21 +41,21 @@ namespace Greenshot { /// The about form /// public partial class AboutForm : AnimatingBaseForm { - private static ILog LOG = LogManager.GetLogger(typeof(AboutForm)); - private Bitmap gBitmap; - private ColorAnimator backgroundAnimation; - private List pixels = new List(); - private List colorFlow = new List(); - private List pixelColors = new List(); - private Random rand = new Random(); - private readonly Color backColor = Color.FromArgb(61, 61, 61); - private readonly Color pixelColor = Color.FromArgb(138, 255, 0); + private static readonly ILog LOG = LogManager.GetLogger(typeof(AboutForm)); + private Bitmap _bitmap; + private readonly ColorAnimator _backgroundAnimation; + private readonly IList _pixels = new List(); + private readonly IList _colorFlow = new List(); + private readonly IList _pixelColors = new List(); + private readonly Random _rand = new Random(); + private readonly Color _backColor = Color.FromArgb(61, 61, 61); + private readonly Color _pixelColor = Color.FromArgb(138, 255, 0); // Variables used for the color-cycle - private int waitFrames = 0; - private int colorIndex = 0; - private int scrollCount = 0; - private bool hasAnimationsLeft; + private int _waitFrames; + private int _colorIndex; + private int _scrollCount; + private bool _hasAnimationsLeft; // Variables are used to define the location of the dots private const int w = 13; @@ -70,7 +70,7 @@ namespace Greenshot { /// /// The location of every dot in the "G" /// - private List gSpots = new List() { + private readonly List gSpots = new List() { // Top row new Point(p2, p1), // 0 new Point(p3, p1), // 1 @@ -116,15 +116,15 @@ namespace Greenshot { // 18 19 20 21 22 23 // The order in which we draw the dots & flow the collors. - List flowOrder = new List() { 4, 3, 2, 1, 0, 5, 6, 7, 8, 9, 10, 14, 15, 18, 19, 20, 21, 22, 23, 16, 17, 13, 12, 11 }; + readonly List flowOrder = new List() { 4, 3, 2, 1, 0, 5, 6, 7, 8, 9, 10, 14, 15, 18, 19, 20, 21, 22, 23, 16, 17, 13, 12, 11 }; /// /// Cleanup all the allocated resources /// private void Cleanup(object sender, EventArgs e) { - if (gBitmap != null) { - gBitmap.Dispose(); - gBitmap = null; + if (_bitmap != null) { + _bitmap.Dispose(); + _bitmap = null; } } @@ -144,22 +144,22 @@ namespace Greenshot { InitializeComponent(); // Only use double-buffering when we are NOT in a Terminal Server session - DoubleBuffered = !isTerminalServerSession; + DoubleBuffered = !IsTerminalServerSession; // Use the self drawn image, first we create the background to be the backcolor (as we animate from this) - gBitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96); - pictureBox1.Image = gBitmap; + _bitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96); + pictureBox1.Image = _bitmap; Version v = Assembly.GetExecutingAssembly().GetName().Version; // Format is like this: AssemblyVersion("Major.Minor.Build.Revision")] - lblTitle.Text = "Greenshot " + v.Major + "." + v.Minor + "." + v.Build + " Build " + v.Revision + (IniConfig.IsPortable ? " Portable" : "") + (" (" + OSInfo.Bits + " bit)"); + lblTitle.Text = "Greenshot " + v.Major + "." + v.Minor + "." + v.Build + " Build " + v.Revision + (IniConfig.IsPortable ? " Portable" : "") + (" (" + OSInfo.Bits) + " bit)"; //Random rand = new Random(); // Number of frames the pixel animation takes int frames = FramesForMillis(2000); // The number of frames the color-cycle waits before it starts - waitFrames = FramesForMillis(6000); + _waitFrames = FramesForMillis(6000); // Every pixel is created after pixelWaitFrames frames, which is increased in the loop. int pixelWaitFrames = FramesForMillis(2000); @@ -174,7 +174,7 @@ namespace Greenshot { int offset = (w - 2) / 2; // If the optimize for Terminal Server is set we make the animation without much ado - if (isTerminalServerSession) { + if (IsTerminalServerSession) { // No animation pixelAnimation = new RectangleAnimator(new Rectangle(gSpot.X, gSpot.Y, w - 2, w - 2), new Rectangle(gSpot.X, gSpot.Y, w - 2, w - 2), 1, EasingType.Cubic, EasingMode.EaseIn); } else { @@ -187,23 +187,23 @@ namespace Greenshot { // Increase the wait frames pixelWaitFrames += FramesForMillis(100); // Add to the list of to be animated pixels - pixels.Add(pixelAnimation); + _pixels.Add(pixelAnimation); // Add a color to the list for this pixel. - pixelColors.Add(pixelColor); + _pixelColors.Add(_pixelColor); } // Make sure the frame "loop" knows we have to animate - hasAnimationsLeft = true; + _hasAnimationsLeft = true; // Pixel Color cycle colors, here we use a pre-animated loop which stores the values. - ColorAnimator pixelColorAnimator = new ColorAnimator(pixelColor, Color.FromArgb(255, 255, 255), 6, EasingType.Quadratic, EasingMode.EaseIn); - pixelColorAnimator.QueueDestinationLeg(pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut); + ColorAnimator pixelColorAnimator = new ColorAnimator(_pixelColor, Color.FromArgb(255, 255, 255), 6, EasingType.Quadratic, EasingMode.EaseIn); + pixelColorAnimator.QueueDestinationLeg(_pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut); do { - colorFlow.Add(pixelColorAnimator.Current); + _colorFlow.Add(pixelColorAnimator.Current); pixelColorAnimator.Next(); - } while (pixelColorAnimator.hasNext); + } while (pixelColorAnimator.HasNext); // color animation for the background - backgroundAnimation = new ColorAnimator(BackColor, backColor, FramesForMillis(5000), EasingType.Linear, EasingMode.EaseIn); + _backgroundAnimation = new ColorAnimator(BackColor, _backColor, FramesForMillis(5000), EasingType.Linear, EasingMode.EaseIn); } /// @@ -227,63 +227,63 @@ namespace Greenshot { /// Called from the AnimatingForm, for every frame /// protected override void Animate() { - if (gBitmap == null) { + if (_bitmap == null) { return; } - if (!isTerminalServerSession) { + if (!IsTerminalServerSession) { // Color cycle - if (waitFrames != 0) { - waitFrames--; + if (_waitFrames != 0) { + _waitFrames--; // Check if there is something else to do, if not we return so we don't occupy the CPU - if (!hasAnimationsLeft) { + if (!_hasAnimationsLeft) { return; } - } else if (scrollCount < (pixelColors.Count + colorFlow.Count)) { + } else if (_scrollCount < _pixelColors.Count + _colorFlow.Count) { // Scroll colors, the scrollCount is the amount of pixels + the amount of colors to cycle. - for (int index = pixelColors.Count - 1; index > 0; index--) { - pixelColors[index] = pixelColors[index - 1]; + for (int index = _pixelColors.Count - 1; index > 0; index--) { + _pixelColors[index] = _pixelColors[index - 1]; } // Keep adding from the colors to cycle until there is nothing left - if (colorIndex < colorFlow.Count) { - pixelColors[0] = colorFlow[colorIndex++]; + if (_colorIndex < _colorFlow.Count) { + _pixelColors[0] = _colorFlow[_colorIndex++]; } - scrollCount++; + _scrollCount++; } else { // Reset values, wait X time for the next one - waitFrames = FramesForMillis(3000 + rand.Next(35000)); - colorIndex = 0; - scrollCount = 0; + _waitFrames = FramesForMillis(3000 + _rand.Next(35000)); + _colorIndex = 0; + _scrollCount = 0; // Check if there is something else to do, if not we return so we don't occupy the CPU - if (!hasAnimationsLeft) { + if (!_hasAnimationsLeft) { return; } } - } else if (!hasAnimationsLeft) { + } else if (!_hasAnimationsLeft) { return; } // Draw the "G" - using (Graphics graphics = Graphics.FromImage(gBitmap)) { + using (Graphics graphics = Graphics.FromImage(_bitmap)) { graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBilinear; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.Clear(backgroundAnimation.Next()); + graphics.Clear(_backgroundAnimation.Next()); graphics.TranslateTransform(2, -2); graphics.RotateTransform(20); - using (SolidBrush brush = new SolidBrush(pixelColor)) { + using (SolidBrush brush = new SolidBrush(_pixelColor)) { int index = 0; // We asume there is nothing to animate in the next Animate loop - hasAnimationsLeft = false; + _hasAnimationsLeft = false; // Pixels of the G - foreach (RectangleAnimator pixel in pixels) { - brush.Color = pixelColors[index++]; + foreach (RectangleAnimator pixel in _pixels) { + brush.Color = _pixelColors[index++]; graphics.FillEllipse(brush, pixel.Current); // If a pixel still has frames left, the hasAnimationsLeft will be true - hasAnimationsLeft = hasAnimationsLeft | pixel.hasNext; + _hasAnimationsLeft = _hasAnimationsLeft | pixel.HasNext; pixel.Next(); } } diff --git a/Greenshot/Forms/CaptureForm.cs b/Greenshot/Forms/CaptureForm.cs index 528cd6515..3c6398ac5 100644 --- a/Greenshot/Forms/CaptureForm.cs +++ b/Greenshot/Forms/CaptureForm.cs @@ -61,9 +61,9 @@ namespace Greenshot.Forms { private int _mX; private int _mY; private Point _mouseMovePos = Point.Empty; - private Point _cursorPos = Point.Empty; - private CaptureMode _captureMode = CaptureMode.None; - private readonly List _windows = new List(); + private Point _cursorPos; + private CaptureMode _captureMode; + private readonly List _windows; private WindowDetails _selectedCaptureWindow; private bool _mouseDown; private Rectangle _captureRect = Rectangle.Empty; @@ -73,7 +73,7 @@ namespace Greenshot.Forms { private RectangleAnimator _windowAnimator; private RectangleAnimator _zoomAnimator; private readonly bool _isZoomerTransparent = Conf.ZoomerOpacity < 1; - private bool _isCtrlPressed = false; + private bool _isCtrlPressed; /// /// Property to access the selected capture rectangle @@ -153,7 +153,7 @@ namespace Greenshot.Forms { // InitializeComponent(); // Only double-buffer when we are not in a TerminalServerSession - DoubleBuffered = !isTerminalServerSession; + DoubleBuffered = !IsTerminalServerSession; Text = "Greenshot capture form"; // Make sure we never capture the captureform @@ -398,7 +398,7 @@ namespace Greenshot.Forms { if (animator == null) { return false; } - return animator.hasNext; + return animator.HasNext; } /// @@ -486,7 +486,7 @@ namespace Greenshot.Forms { invalidateRectangle = new Rectangle(x1,y1, x2-x1, y2-y1); Invalidate(invalidateRectangle); } else if (_captureMode != CaptureMode.Window) { - if (!isTerminalServerSession) { + if (!IsTerminalServerSession) { Rectangle allScreenBounds = WindowCapture.GetScreenBounds(); allScreenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location); if (verticalMove) { @@ -570,7 +570,7 @@ namespace Greenshot.Forms { screenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(screenBounds.Location); int relativeZoomSize = Math.Min(screenBounds.Width, screenBounds.Height) / 5; // Make sure the final size is a plural of 4, this makes it look better - relativeZoomSize = relativeZoomSize - (relativeZoomSize % 4); + relativeZoomSize = relativeZoomSize - relativeZoomSize % 4; Size zoomSize = new Size(relativeZoomSize, relativeZoomSize); Point zoomOffset = new Point(20, 20); @@ -652,9 +652,9 @@ namespace Greenshot.Forms { // Calculate some values int pixelThickness = destinationRectangle.Width / sourceRectangle.Width; int halfWidth = destinationRectangle.Width / 2; - int halfWidthEnd = (destinationRectangle.Width / 2) - (pixelThickness / 2); + int halfWidthEnd = destinationRectangle.Width / 2 - pixelThickness / 2; int halfHeight = destinationRectangle.Height / 2; - int halfHeightEnd = (destinationRectangle.Height / 2) - (pixelThickness / 2); + int halfHeightEnd = destinationRectangle.Height / 2 - pixelThickness / 2; int drawAtHeight = destinationRectangle.Y + halfHeight; int drawAtWidth = destinationRectangle.X + halfWidth; @@ -673,8 +673,8 @@ namespace Greenshot.Forms { graphics.DrawLine(pen, destinationRectangle.X + halfWidthEnd + 2 * padding, drawAtHeight, destinationRectangle.X + destinationRectangle.Width - padding, drawAtHeight); // Fix offset for drawing the white rectangle around the crosshair-lines - drawAtHeight -= (pixelThickness / 2); - drawAtWidth -= (pixelThickness / 2); + drawAtHeight -= pixelThickness / 2; + drawAtWidth -= pixelThickness / 2; // Fix off by one error with the DrawRectangle pixelThickness -= 1; // Change the color and the pen width @@ -762,7 +762,7 @@ namespace Greenshot.Forms { graphics.DrawPath(rulerPen, p); graphics.DrawString(captureWidth, rulerFont, rulerPen.Brush, fixedRect.X + (fixedRect.Width / 2 - hSpace / 2) + 3, fixedRect.Y - dist - 7); graphics.DrawLine(rulerPen, fixedRect.X, fixedRect.Y - dist, fixedRect.X + (fixedRect.Width / 2 - hSpace / 2), fixedRect.Y - dist); - graphics.DrawLine(rulerPen, fixedRect.X + (fixedRect.Width / 2 + hSpace / 2), fixedRect.Y - dist, fixedRect.X + fixedRect.Width, fixedRect.Y - dist); + graphics.DrawLine(rulerPen, fixedRect.X + fixedRect.Width / 2 + hSpace / 2, fixedRect.Y - dist, fixedRect.X + fixedRect.Width, fixedRect.Y - dist); graphics.DrawLine(rulerPen, fixedRect.X, fixedRect.Y - dist - 3, fixedRect.X, fixedRect.Y - dist + 3); graphics.DrawLine(rulerPen, fixedRect.X + fixedRect.Width, fixedRect.Y - dist - 3, fixedRect.X + fixedRect.Width, fixedRect.Y - dist + 3); } @@ -780,7 +780,7 @@ namespace Greenshot.Forms { graphics.DrawPath(rulerPen, p); graphics.DrawString(captureHeight, rulerFont, rulerPen.Brush, fixedRect.X - measureHeight.Width + 1, fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2) + 2); graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y, fixedRect.X - dist, fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2)); - graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y + (fixedRect.Height / 2 + vSpace / 2), fixedRect.X - dist, fixedRect.Y + fixedRect.Height); + graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y + fixedRect.Height / 2 + vSpace / 2, fixedRect.X - dist, fixedRect.Y + fixedRect.Height); graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y, fixedRect.X - dist + 3, fixedRect.Y); graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y + fixedRect.Height, fixedRect.X - dist + 3, fixedRect.Y + fixedRect.Height); } @@ -797,7 +797,7 @@ namespace Greenshot.Forms { string sizeText; if (_captureMode == CaptureMode.Region) { // correct the GUI width to real width for the shown size - sizeText = (_captureRect.Width + 1) + " x " + (_captureRect.Height + 1); + sizeText = _captureRect.Width + 1 + " x " + (_captureRect.Height + 1); } else { sizeText = _captureRect.Width + " x " + _captureRect.Height; } @@ -806,7 +806,7 @@ namespace Greenshot.Forms { SizeF extent = graphics.MeasureString( sizeText, sizeFont ); float hRatio = _captureRect.Height / (extent.Height * 2); float wRatio = _captureRect.Width / (extent.Width * 2); - float ratio = ( hRatio < wRatio ? hRatio : wRatio ); + float ratio = hRatio < wRatio ? hRatio : wRatio; float newSize = sizeFont.Size * ratio; if ( newSize >= 4 ) { @@ -816,13 +816,13 @@ namespace Greenshot.Forms { } // Draw the size. using (Font newSizeFont = new Font(FontFamily.GenericSansSerif, newSize, FontStyle.Bold)) { - PointF sizeLocation = new PointF(fixedRect.X + (_captureRect.Width / 2) - (extent.Width / 2), fixedRect.Y + (_captureRect.Height / 2) - (newSizeFont.GetHeight() / 2)); + PointF sizeLocation = new PointF(fixedRect.X + _captureRect.Width / 2 - extent.Width / 2, fixedRect.Y + _captureRect.Height / 2 - newSizeFont.GetHeight() / 2); graphics.DrawString(sizeText, newSizeFont, Brushes.LightSeaGreen, sizeLocation); } } } } else { - if (!isTerminalServerSession) { + if (!IsTerminalServerSession) { using (Pen pen = new Pen(Color.LightSeaGreen)) { pen.DashStyle = DashStyle.Dot; Rectangle screenBounds = _capture.ScreenBounds; @@ -852,7 +852,7 @@ namespace Greenshot.Forms { const int zoomSourceWidth = 25; const int zoomSourceHeight = 25; - Rectangle sourceRectangle = new Rectangle(_cursorPos.X - (zoomSourceWidth / 2), _cursorPos.Y - (zoomSourceHeight / 2), zoomSourceWidth, zoomSourceHeight); + Rectangle sourceRectangle = new Rectangle(_cursorPos.X - zoomSourceWidth / 2, _cursorPos.Y - zoomSourceHeight / 2, zoomSourceWidth, zoomSourceHeight); Rectangle destinationRectangle = _zoomAnimator.Current; destinationRectangle.Offset(_cursorPos); diff --git a/Greenshot/Forms/ColorDialog.cs b/Greenshot/Forms/ColorDialog.cs index 2f630d064..00f756317 100644 --- a/Greenshot/Forms/ColorDialog.cs +++ b/Greenshot/Forms/ColorDialog.cs @@ -35,7 +35,7 @@ namespace Greenshot { /// public partial class ColorDialog : BaseForm { private static ColorDialog uniqueInstance; - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); private ColorDialog() { SuspendLayout(); @@ -57,7 +57,7 @@ namespace Greenshot { private readonly List public partial class ImageEditorForm : BaseForm, IImageEditor { private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageEditorForm)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); - private static List ignoreDestinations = new List() { PickerDestination.DESIGNATION, EditorDestination.DESIGNATION }; - private static List editorList = new List(); + private static readonly EditorConfiguration EditorConfiguration = IniConfig.GetIniSection(); + private static readonly List IgnoreDestinations = new List() { PickerDestination.DESIGNATION, EditorDestination.DESIGNATION }; + private static readonly List EditorList = new List(); - private Surface surface; - private GreenshotToolStripButton[] toolbarButtons; + private Surface _surface; + private GreenshotToolStripButton[] _toolbarButtons; - private static string[] SUPPORTED_CLIPBOARD_FORMATS = {typeof(string).FullName, "Text", typeof(DrawableContainerList).FullName}; + private static readonly string[] SupportedClipboardFormats = {typeof(string).FullName, "Text", typeof(DrawableContainerList).FullName}; - private bool originalBoldCheckState = false; - private bool originalItalicCheckState = false; + private bool _originalBoldCheckState; + private bool _originalItalicCheckState; // whether part of the editor controls are disabled depending on selected item(s) - private bool controlsDisabledDueToConfirmable = false; + private bool _controlsDisabledDueToConfirmable; /// /// An Implementation for the IImageEditor, this way Plugins have access to the HWND handles wich can be used with Win32 API calls. @@ -74,54 +74,58 @@ namespace Greenshot { public static List Editors { get { try { - editorList.Sort(delegate(IImageEditor e1, IImageEditor e2) { - return e1.Surface.CaptureDetails.Title.CompareTo(e2.Surface.CaptureDetails.Title); + EditorList.Sort(delegate(IImageEditor e1, IImageEditor e2) { + return String.Compare(e1.Surface.CaptureDetails.Title, e2.Surface.CaptureDetails.Title, StringComparison.Ordinal); }); } catch(Exception ex) { LOG.Warn("Sorting of editors failed.", ex); } - return editorList; + return EditorList; } } public ImageEditorForm(ISurface iSurface, bool outputMade) { - editorList.Add(this); + EditorList.Add(this); // // The InitializeComponent() call is required for Windows Forms designer support. // ManualLanguageApply = true; InitializeComponent(); - + Load += delegate { - var thread = new Thread(delegate() {AddDestinations();}); - thread.Name = "add destinations"; + var thread = new Thread(AddDestinations) + { + Name = "add destinations" + }; thread.Start(); }; // Make sure the editor is placed on the same location as the last editor was on close - WindowDetails thisForm = new WindowDetails(Handle); - thisForm.WindowPlacement = editorConfiguration.GetEditorPlacement(); + WindowDetails thisForm = new WindowDetails(Handle) + { + WindowPlacement = EditorConfiguration.GetEditorPlacement() + }; // init surface Surface = iSurface; // Intial "saved" flag for asking if the image needs to be save - surface.Modified = !outputMade; + _surface.Modified = !outputMade; - updateUI(); + UpdateUi(); // Workaround: As the cursor is (mostly) selected on the surface a funny artifact is visible, this fixes it. - hideToolstripItems(); + HideToolstripItems(); } /// /// Remove the current surface /// private void RemoveSurface() { - if (surface != null) { - panel1.Controls.Remove(surface as Control); - surface.Dispose(); - surface = null; + if (_surface != null) { + panel1.Controls.Remove(_surface); + _surface.Dispose(); + _surface = null; } } @@ -138,30 +142,33 @@ namespace Greenshot { panel1.Height = 10; panel1.Width = 10; - surface = newSurface as Surface; - panel1.Controls.Add(surface as Surface); + _surface = newSurface as Surface; + panel1.Controls.Add(_surface); Image backgroundForTransparency = GreenshotResources.getImage("Checkerboard.Image"); - surface.TransparencyBackgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile); + if (_surface != null) + { + _surface.TransparencyBackgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile); - surface.MovingElementChanged += delegate { - refreshEditorControls(); - }; - surface.DrawingModeChanged += surface_DrawingModeChanged; - surface.SurfaceSizeChanged += SurfaceSizeChanged; - surface.SurfaceMessage += SurfaceMessageReceived; - surface.FieldAggregator.FieldChanged += FieldAggregatorFieldChanged; - SurfaceSizeChanged(Surface, null); + _surface.MovingElementChanged += delegate { + RefreshEditorControls(); + }; + _surface.DrawingModeChanged += surface_DrawingModeChanged; + _surface.SurfaceSizeChanged += SurfaceSizeChanged; + _surface.SurfaceMessage += SurfaceMessageReceived; + _surface.FieldAggregator.FieldChanged += FieldAggregatorFieldChanged; + SurfaceSizeChanged(Surface, null); - bindFieldControls(); - refreshEditorControls(); - // Fix title - if (surface != null && surface.CaptureDetails != null && surface.CaptureDetails.Title != null) { - Text = surface.CaptureDetails.Title + " - " + Language.GetString(LangKey.editor_title); + BindFieldControls(); + RefreshEditorControls(); + // Fix title + if (_surface != null && _surface.CaptureDetails != null && _surface.CaptureDetails.Title != null) { + Text = _surface.CaptureDetails.Title + " - " + Language.GetString(LangKey.editor_title); + } } WindowDetails.ToForeground(Handle); } - private void updateUI() { + private void UpdateUi() { // Disable access to the settings, for feature #3521446 preferencesToolStripMenuItem.Visible = !coreConfiguration.DisableSettings; toolStripSeparator12.Visible = !coreConfiguration.DisableSettings; @@ -181,7 +188,7 @@ namespace Greenshot { obfuscateModeButton.DropDownItemClicked += FilterPresetDropDownItemClicked; highlightModeButton.DropDownItemClicked += FilterPresetDropDownItemClicked; - toolbarButtons = new[] { btnCursor, btnRect, btnEllipse, btnText, btnLine, btnArrow, btnFreehand, btnHighlight, btnObfuscate, btnCrop, btnStepLabel, btnSpeechBubble }; + _toolbarButtons = new[] { btnCursor, btnRect, btnEllipse, btnText, btnLine, btnArrow, btnFreehand, btnHighlight, btnObfuscate, btnCrop, btnStepLabel, btnSpeechBubble }; //toolbarDropDownButtons = new ToolStripDropDownButton[]{btnBlur, btnPixeliate, btnTextHighlighter, btnAreaHighlighter, btnMagnifier}; pluginToolStripMenuItem.Visible = pluginToolStripMenuItem.DropDownItems.Count > 0; @@ -198,7 +205,7 @@ namespace Greenshot { /// /// /// - void propertiesToolStrip_Paint(object sender, PaintEventArgs e) { + private void PropertiesToolStrip_Paint(object sender, PaintEventArgs e) { using (Pen cbBorderPen = new Pen(SystemColors.ActiveBorder)) { // Loop over all items in the propertiesToolStrip foreach (ToolStripItem item in propertiesToolStrip.Items) { @@ -208,10 +215,13 @@ namespace Greenshot { continue; } // Calculate the rectangle - Rectangle r = new Rectangle(cb.ComboBox.Location.X - 1, cb.ComboBox.Location.Y - 1, cb.ComboBox.Size.Width + 1, cb.ComboBox.Size.Height + 1); + if (cb.ComboBox != null) + { + Rectangle r = new Rectangle(cb.ComboBox.Location.X - 1, cb.ComboBox.Location.Y - 1, cb.ComboBox.Size.Width + 1, cb.ComboBox.Size.Height + 1); - // Draw the rectangle - e.Graphics.DrawRectangle(cbBorderPen, r); + // Draw the rectangle + e.Graphics.DrawRectangle(cbBorderPen, r); + } } } } @@ -219,7 +229,7 @@ namespace Greenshot { /// /// Get all the destinations and display them in the file menu and the buttons /// - void AddDestinations() { + private void AddDestinations() { Invoke((MethodInvoker)delegate { // Create export buttons foreach(IDestination destination in DestinationHelper.GetAllDestinations()) { @@ -242,29 +252,34 @@ namespace Greenshot { }); } - void AddDestinationButton(IDestination toolstripDestination) { + private void AddDestinationButton(IDestination toolstripDestination) { if (toolstripDestination.isDynamic) { - ToolStripSplitButton destinationButton = new ToolStripSplitButton(); + ToolStripSplitButton destinationButton = new ToolStripSplitButton + { + DisplayStyle = ToolStripItemDisplayStyle.Image, + Size = new Size(23, 22), + Text = toolstripDestination.Description, + Image = toolstripDestination.DisplayIcon + }; //ToolStripDropDownButton destinationButton = new ToolStripDropDownButton(); - destinationButton.DisplayStyle = ToolStripItemDisplayStyle.Image; - destinationButton.Size = new Size(23, 22); - destinationButton.Text = toolstripDestination.Description; - destinationButton.Image = toolstripDestination.DisplayIcon; - ToolStripMenuItem defaultItem = new ToolStripMenuItem(toolstripDestination.Description); - defaultItem.Tag = toolstripDestination; - defaultItem.Image = toolstripDestination.DisplayIcon; + ToolStripMenuItem defaultItem = new ToolStripMenuItem(toolstripDestination.Description) + { + Tag = toolstripDestination, + Image = toolstripDestination.DisplayIcon + }; defaultItem.Click += delegate { - toolstripDestination.ExportCapture(true, surface, surface.CaptureDetails); + toolstripDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; // The ButtonClick, this is for the icon, gets the current default item - destinationButton.ButtonClick += delegate(object sender, EventArgs e) { - toolstripDestination.ExportCapture(true, surface, surface.CaptureDetails); + destinationButton.ButtonClick += delegate { + toolstripDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; // Generate the entries for the drop down - destinationButton.DropDownOpening += delegate(object sender, EventArgs e) { + destinationButton.DropDownOpening += delegate + { ClearItems(destinationButton.DropDownItems); destinationButton.DropDownItems.Add(defaultItem); @@ -278,7 +293,7 @@ namespace Greenshot { destinationMenuItem.Tag = closureFixedDestination; destinationMenuItem.Image = closureFixedDestination.DisplayIcon; destinationMenuItem.Click += delegate { - closureFixedDestination.ExportCapture(true, surface, surface.CaptureDetails); + closureFixedDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; destinationButton.DropDownItems.Add(destinationMenuItem); } @@ -294,8 +309,8 @@ namespace Greenshot { destinationButton.Size = new Size(23, 22); destinationButton.Text = toolstripDestination.Description; destinationButton.Image = toolstripDestination.DisplayIcon; - destinationButton.Click += delegate(object sender, EventArgs e) { - toolstripDestination.ExportCapture(true, surface, surface.CaptureDetails); + destinationButton.Click += delegate { + toolstripDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; } } @@ -315,12 +330,12 @@ namespace Greenshot { items.Clear(); } - void FileMenuDropDownOpening(object sender, EventArgs eventArgs) { + private void FileMenuDropDownOpening(object sender, EventArgs eventArgs) { ClearItems(fileStripMenuItem.DropDownItems); // Add the destinations foreach(IDestination destination in DestinationHelper.GetAllDestinations()) { - if (ignoreDestinations.Contains(destination.Designation)) { + if (IgnoreDestinations.Contains(destination.Designation)) { continue; } if (!destination.isActive) { @@ -347,7 +362,7 @@ namespace Greenshot { /// private void SurfaceMessageReceived(object sender, SurfaceMessageEventArgs eventArgs) { if (InvokeRequired) { - this.Invoke(new SurfaceMessageReceivedThreadSafeDelegate(SurfaceMessageReceived), new object[] { sender, eventArgs }); + Invoke(new SurfaceMessageReceivedThreadSafeDelegate(SurfaceMessageReceived), new object[] { sender, eventArgs }); } else { string dateTime = DateTime.Now.ToLongTimeString(); // TODO: Fix that we only open files, like in the tooltip @@ -372,17 +387,18 @@ namespace Greenshot { /// /// This is called when the size of the surface chances, used for resizing and displaying the size information /// - /// + /// + /// private void SurfaceSizeChanged(object sender, EventArgs e) { - if (editorConfiguration.MatchSizeToCapture) { + if (EditorConfiguration.MatchSizeToCapture) { // Set editor's initial size to the size of the surface plus the size of the chrome Size imageSize = Surface.Image.Size; Size currentFormSize = Size; Size currentImageClientSize = panel1.ClientSize; int minimumFormWidth = 650; int minimumFormHeight = 530; - int newWidth = Math.Max(minimumFormWidth, (currentFormSize.Width - currentImageClientSize.Width) + imageSize.Width); - int newHeight = Math.Max(minimumFormHeight, (currentFormSize.Height - currentImageClientSize.Height) + imageSize.Height); + int newWidth = Math.Max(minimumFormWidth, currentFormSize.Width - currentImageClientSize.Width + imageSize.Width); + int newHeight = Math.Max(minimumFormHeight, currentFormSize.Height - currentImageClientSize.Height + imageSize.Height); Size = new Size(newWidth, newHeight); } dimensionsLabel.Text = Surface.Image.Width + "x" + Surface.Image.Height; @@ -391,7 +407,7 @@ namespace Greenshot { public ISurface Surface { get { - return surface; + return _surface; } set { SetSurface(value); @@ -403,7 +419,7 @@ namespace Greenshot { if (fullpath != null && (fullpath.EndsWith(".ico") || fullpath.EndsWith(".wmf"))) { fullpath = null; } - surface.LastSaveFullPath = fullpath; + _surface.LastSaveFullPath = fullpath; if (fullpath == null) { return; @@ -411,8 +427,8 @@ namespace Greenshot { updateStatusLabel(Language.GetFormattedString(LangKey.editor_imagesaved, fullpath), fileSavedStatusContextMenu); Text = Path.GetFileName(fullpath) + " - " + Language.GetString(LangKey.editor_title); } - - void surface_DrawingModeChanged(object source, SurfaceDrawingModeEventArgs eventArgs) { + + private void surface_DrawingModeChanged(object source, SurfaceDrawingModeEventArgs eventArgs) { switch (eventArgs.DrawingMode) { case DrawingModes.None: SetButtonChecked(btnCursor); @@ -460,11 +476,11 @@ namespace Greenshot { */ public Image GetImageForExport() { - return surface.GetImageForExport(); + return _surface.GetImageForExport(); } public ICaptureDetails CaptureDetails { - get { return surface.CaptureDetails; } + get { return _surface.CaptureDetails; } } public ToolStripMenuItem GetPluginMenuItem() { @@ -477,254 +493,253 @@ namespace Greenshot { #endregion #region filesystem options - void BtnSaveClick(object sender, EventArgs e) { + + private void BtnSaveClick(object sender, EventArgs e) { string destinationDesignation = FileDestination.DESIGNATION; - if (surface.LastSaveFullPath == null) { + if (_surface.LastSaveFullPath == null) { destinationDesignation = FileWithDialogDestination.DESIGNATION; } - DestinationHelper.ExportCapture(true, destinationDesignation, surface, surface.CaptureDetails); - } - - void BtnClipboardClick(object sender, EventArgs e) { - DestinationHelper.ExportCapture(true, ClipboardDestination.DESIGNATION, surface, surface.CaptureDetails); + DestinationHelper.ExportCapture(true, destinationDesignation, _surface, _surface.CaptureDetails); } - void BtnPrintClick(object sender, EventArgs e) { + private void BtnClipboardClick(object sender, EventArgs e) { + DestinationHelper.ExportCapture(true, ClipboardDestination.DESIGNATION, _surface, _surface.CaptureDetails); + } + + private void BtnPrintClick(object sender, EventArgs e) { // The BeginInvoke is a solution for the printdialog not having focus BeginInvoke((MethodInvoker) delegate { - DestinationHelper.ExportCapture(true, PrinterDestination.DESIGNATION, surface, surface.CaptureDetails); + DestinationHelper.ExportCapture(true, PrinterDestination.DESIGNATION, _surface, _surface.CaptureDetails); }); } - void CloseToolStripMenuItemClick(object sender, EventArgs e) { + private void CloseToolStripMenuItemClick(object sender, EventArgs e) { Close(); } #endregion #region drawing options - void BtnEllipseClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Ellipse; - refreshFieldControls(); - } - - void BtnCursorClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.None; - refreshFieldControls(); - } - - void BtnRectClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Rect; - refreshFieldControls(); - } - - void BtnTextClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Text; - refreshFieldControls(); + + private void BtnEllipseClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Ellipse; + RefreshFieldControls(); } - void BtnSpeechBubbleClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.SpeechBubble; - refreshFieldControls(); - } - void BtnStepLabelClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.StepLabel; - refreshFieldControls(); - } - - void BtnLineClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Line; - refreshFieldControls(); - } - - void BtnArrowClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Arrow; - refreshFieldControls(); - } - - void BtnCropClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Crop; - refreshFieldControls(); - } - - void BtnHighlightClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Highlight; - refreshFieldControls(); - } - - void BtnObfuscateClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Obfuscate; - refreshFieldControls(); + private void BtnCursorClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.None; + RefreshFieldControls(); } - void BtnFreehandClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Path; - refreshFieldControls(); + private void BtnRectClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Rect; + RefreshFieldControls(); } - - void SetButtonChecked(ToolStripButton btn) { + + private void BtnTextClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Text; + RefreshFieldControls(); + } + + private void BtnSpeechBubbleClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.SpeechBubble; + RefreshFieldControls(); + } + + private void BtnStepLabelClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.StepLabel; + RefreshFieldControls(); + } + + private void BtnLineClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Line; + RefreshFieldControls(); + } + + private void BtnArrowClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Arrow; + RefreshFieldControls(); + } + + private void BtnCropClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Crop; + RefreshFieldControls(); + } + + private void BtnHighlightClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Highlight; + RefreshFieldControls(); + } + + private void BtnObfuscateClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Obfuscate; + RefreshFieldControls(); + } + + private void BtnFreehandClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Path; + RefreshFieldControls(); + } + + private void SetButtonChecked(ToolStripButton btn) { UncheckAllToolButtons(); btn.Checked = true; } private void UncheckAllToolButtons() { - if (toolbarButtons != null) { - foreach (ToolStripButton butt in toolbarButtons) { + if (_toolbarButtons != null) { + foreach (GreenshotToolStripButton butt in _toolbarButtons) { butt.Checked = false; } } } - - void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) { BtnRectClick(sender, e); } - void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) { + private void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) { BtnFreehandClick(sender, e); } - - void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) { BtnEllipseClick(sender, e); } - - void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) { BtnTextClick(sender, e); } - - void AddSpeechBubbleToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddSpeechBubbleToolStripMenuItemClick(object sender, EventArgs e) { BtnSpeechBubbleClick(sender, e); } - - void AddCounterToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddCounterToolStripMenuItemClick(object sender, EventArgs e) { BtnStepLabelClick(sender, e); } - - void DrawLineToolStripMenuItemClick(object sender, EventArgs e) { + + private void DrawLineToolStripMenuItemClick(object sender, EventArgs e) { BtnLineClick(sender, e); } - - void DrawArrowToolStripMenuItemClick(object sender, EventArgs e) { + + private void DrawArrowToolStripMenuItemClick(object sender, EventArgs e) { BtnArrowClick(sender, e); } - - void DrawHighlightToolStripMenuItemClick(object sender, EventArgs e) { - BtnHighlightClick(sender, e); - } - - void BlurToolStripMenuItemClick(object sender, EventArgs e) { - BtnObfuscateClick(sender, e); - } - - void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) { - surface.RemoveSelectedElements(); + + private void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) { + _surface.RemoveSelectedElements(); } - void BtnDeleteClick(object sender, EventArgs e) { + private void BtnDeleteClick(object sender, EventArgs e) { RemoveObjectToolStripMenuItemClick(sender, e); } #endregion #region copy&paste options - void CutToolStripMenuItemClick(object sender, EventArgs e) { - surface.CutSelectedElements(); - updateClipboardSurfaceDependencies(); + + private void CutToolStripMenuItemClick(object sender, EventArgs e) { + _surface.CutSelectedElements(); + UpdateClipboardSurfaceDependencies(); } - void BtnCutClick(object sender, EventArgs e) { + private void BtnCutClick(object sender, EventArgs e) { CutToolStripMenuItemClick(sender, e); } - - void CopyToolStripMenuItemClick(object sender, EventArgs e) { - surface.CopySelectedElements(); - updateClipboardSurfaceDependencies(); + + private void CopyToolStripMenuItemClick(object sender, EventArgs e) { + _surface.CopySelectedElements(); + UpdateClipboardSurfaceDependencies(); } - void BtnCopyClick(object sender, EventArgs e) { + private void BtnCopyClick(object sender, EventArgs e) { CopyToolStripMenuItemClick(sender, e); } - - void PasteToolStripMenuItemClick(object sender, EventArgs e) { - surface.PasteElementFromClipboard(); - updateClipboardSurfaceDependencies(); + + private void PasteToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PasteElementFromClipboard(); + UpdateClipboardSurfaceDependencies(); } - void BtnPasteClick(object sender, EventArgs e) { + private void BtnPasteClick(object sender, EventArgs e) { PasteToolStripMenuItemClick(sender, e); } - void UndoToolStripMenuItemClick(object sender, EventArgs e) { - surface.Undo(); - updateUndoRedoSurfaceDependencies(); + private void UndoToolStripMenuItemClick(object sender, EventArgs e) { + _surface.Undo(); + UpdateUndoRedoSurfaceDependencies(); } - void BtnUndoClick(object sender, EventArgs e) { + private void BtnUndoClick(object sender, EventArgs e) { UndoToolStripMenuItemClick(sender, e); } - void RedoToolStripMenuItemClick(object sender, EventArgs e) { - surface.Redo(); - updateUndoRedoSurfaceDependencies(); + private void RedoToolStripMenuItemClick(object sender, EventArgs e) { + _surface.Redo(); + UpdateUndoRedoSurfaceDependencies(); } - void BtnRedoClick(object sender, EventArgs e) { + private void BtnRedoClick(object sender, EventArgs e) { RedoToolStripMenuItemClick(sender, e); } - void DuplicateToolStripMenuItemClick(object sender, EventArgs e) { - surface.DuplicateSelectedElements(); - updateClipboardSurfaceDependencies(); + private void DuplicateToolStripMenuItemClick(object sender, EventArgs e) { + _surface.DuplicateSelectedElements(); + UpdateClipboardSurfaceDependencies(); } #endregion #region element properties - void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) { - surface.PullElementsUp(); + + private void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PullElementsUp(); } - - void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) { - surface.PushElementsDown(); + + private void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PushElementsDown(); } - - void UpToTopToolStripMenuItemClick(object sender, EventArgs e) { - surface.PullElementsToTop(); + + private void UpToTopToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PullElementsToTop(); } - - void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) { - surface.PushElementsToBottom(); + + private void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PushElementsToBottom(); } #endregion #region help - void HelpToolStripMenuItem1Click(object sender, EventArgs e) { + + private void HelpToolStripMenuItem1Click(object sender, EventArgs e) { HelpFileLoader.LoadHelp(); } - void AboutToolStripMenuItemClick(object sender, EventArgs e) { + private void AboutToolStripMenuItemClick(object sender, EventArgs e) { MainForm.Instance.ShowAbout(); } - void PreferencesToolStripMenuItemClick(object sender, EventArgs e) { + private void PreferencesToolStripMenuItemClick(object sender, EventArgs e) { MainForm.Instance.ShowSetting(); } - void BtnSettingsClick(object sender, EventArgs e) { + private void BtnSettingsClick(object sender, EventArgs e) { PreferencesToolStripMenuItemClick(sender, e); } - void BtnHelpClick(object sender, EventArgs e) { + private void BtnHelpClick(object sender, EventArgs e) { HelpToolStripMenuItem1Click(sender, e); } #endregion #region image editor event handlers - void ImageEditorFormActivated(object sender, EventArgs e) { - updateClipboardSurfaceDependencies(); - updateUndoRedoSurfaceDependencies(); + + private void ImageEditorFormActivated(object sender, EventArgs e) { + UpdateClipboardSurfaceDependencies(); + UpdateUndoRedoSurfaceDependencies(); } - void ImageEditorFormFormClosing(object sender, FormClosingEventArgs e) { - if (surface.Modified && !editorConfiguration.SuppressSaveDialogAtClose) { + private void ImageEditorFormFormClosing(object sender, FormClosingEventArgs e) { + if (_surface.Modified && !EditorConfiguration.SuppressSaveDialogAtClose) { // Make sure the editor is visible WindowDetails.ToForeground(Handle); @@ -741,20 +756,20 @@ namespace Greenshot { if (result.Equals(DialogResult.Yes)) { BtnSaveClick(sender,e); // Check if the save was made, if not it was cancelled so we cancel the closing - if (surface.Modified) { + if (_surface.Modified) { e.Cancel = true; return; } } } // persist our geometry string. - editorConfiguration.SetEditorPlacement(new WindowDetails(Handle).WindowPlacement); + EditorConfiguration.SetEditorPlacement(new WindowDetails(Handle).WindowPlacement); IniConfig.Save(); // remove from the editor list - editorList.Remove(this); + EditorList.Remove(this); - surface.Dispose(); + _surface.Dispose(); GC.Collect(); if (coreConfiguration.MinimizeWorkingSetSize) { @@ -762,11 +777,11 @@ namespace Greenshot { } } - void ImageEditorFormKeyDown(object sender, KeyEventArgs e) { + private void ImageEditorFormKeyDown(object sender, KeyEventArgs e) { // LOG.Debug("Got key event "+e.KeyCode + ", " + e.Modifiers); // avoid conflict with other shortcuts and // make sure there's no selected element claiming input focus - if(e.Modifiers.Equals(Keys.None) && !surface.KeysLocked) { + if(e.Modifiers.Equals(Keys.None) && !_surface.KeysLocked) { switch(e.KeyCode) { case Keys.Escape: BtnCursorClick(sender, e); @@ -854,7 +869,7 @@ namespace Greenshot { #region key handling protected override bool ProcessKeyPreview(ref Message msg) { // disable default key handling if surface has requested a lock - if (!surface.KeysLocked) { + if (!_surface.KeysLocked) { return base.ProcessKeyPreview(ref msg); } return false; @@ -862,13 +877,13 @@ namespace Greenshot { protected override bool ProcessCmdKey(ref Message msg, Keys keys) { // disable default key handling if surface has requested a lock - if (!surface.KeysLocked) { + if (!_surface.KeysLocked) { // Go through the destinations to check the EditorShortcut Keys // this way the menu entries don't need to be enabled. // This also fixes bugs #3526974 & #3527020 foreach (IDestination destination in DestinationHelper.GetAllDestinations()) { - if (ignoreDestinations.Contains(destination.Designation)) { + if (IgnoreDestinations.Contains(destination.Designation)) { continue; } if (!destination.isActive) { @@ -876,11 +891,11 @@ namespace Greenshot { } if (destination.EditorShortcutKeys == keys) { - destination.ExportCapture(true, surface, surface.CaptureDetails); + destination.ExportCapture(true, _surface, _surface.CaptureDetails); return true; } } - if (!surface.ProcessCmdKey(keys)) { + if (!_surface.ProcessCmdKey(keys)) { return base.ProcessCmdKey(ref msg, keys); } } @@ -890,30 +905,30 @@ namespace Greenshot { #region helpers - private void updateUndoRedoSurfaceDependencies() { - if (surface == null) { + private void UpdateUndoRedoSurfaceDependencies() { + if (_surface == null) { return; } - bool canUndo = surface.CanUndo; + bool canUndo = _surface.CanUndo; btnUndo.Enabled = canUndo; undoToolStripMenuItem.Enabled = canUndo; string undoAction = ""; if (canUndo) { - if (surface.UndoActionLanguageKey != LangKey.none) { - undoAction = Language.GetString(surface.UndoActionLanguageKey); + if (_surface.UndoActionLanguageKey != LangKey.none) { + undoAction = Language.GetString(_surface.UndoActionLanguageKey); } } string undoText = Language.GetFormattedString(LangKey.editor_undo, undoAction); btnUndo.Text = undoText; undoToolStripMenuItem.Text = undoText; - bool canRedo = surface.CanRedo; + bool canRedo = _surface.CanRedo; btnRedo.Enabled = canRedo; redoToolStripMenuItem.Enabled = canRedo; string redoAction = ""; if (canRedo) { - if (surface.RedoActionLanguageKey != LangKey.none) { - redoAction = Language.GetString(surface.RedoActionLanguageKey); + if (_surface.RedoActionLanguageKey != LangKey.none) { + redoAction = Language.GetString(_surface.RedoActionLanguageKey); } } string redoText = Language.GetFormattedString(LangKey.editor_redo, redoAction); @@ -922,13 +937,13 @@ namespace Greenshot { } - private void updateClipboardSurfaceDependencies() { - if (surface == null) { + private void UpdateClipboardSurfaceDependencies() { + if (_surface == null) { return; } // check dependencies for the Surface - bool hasItems = surface.HasSelectedElements; - bool actionAllowedForSelection = hasItems && !controlsDisabledDueToConfirmable; + bool hasItems = _surface.HasSelectedElements; + bool actionAllowedForSelection = hasItems && !_controlsDisabledDueToConfirmable; // buttons btnCut.Enabled = actionAllowedForSelection; @@ -942,9 +957,9 @@ namespace Greenshot { duplicateToolStripMenuItem.Enabled = actionAllowedForSelection; // check dependencies for the Clipboard - bool hasClipboard = ClipboardHelper.ContainsFormat(SUPPORTED_CLIPBOARD_FORMATS) || ClipboardHelper.ContainsImage(); - btnPaste.Enabled = hasClipboard && !controlsDisabledDueToConfirmable; - pasteToolStripMenuItem.Enabled = hasClipboard && !controlsDisabledDueToConfirmable; + bool hasClipboard = ClipboardHelper.ContainsFormat(SupportedClipboardFormats) || ClipboardHelper.ContainsImage(); + btnPaste.Enabled = hasClipboard && !_controlsDisabledDueToConfirmable; + pasteToolStripMenuItem.Enabled = hasClipboard && !_controlsDisabledDueToConfirmable; } #endregion @@ -958,25 +973,27 @@ namespace Greenshot { private void updateStatusLabel(string text) { updateStatusLabel(text, null); } - private void clearStatusLabel() { + private void ClearStatusLabel() { updateStatusLabel(null, null); } - - void StatusLabelClicked(object sender, MouseEventArgs e) { + + private void StatusLabelClicked(object sender, MouseEventArgs e) { ToolStrip ss = (StatusStrip)((ToolStripStatusLabel)sender).Owner; if(ss.ContextMenuStrip != null) { ss.ContextMenuStrip.Show(ss, e.X, e.Y); } } - - void CopyPathMenuItemClick(object sender, EventArgs e) { - ClipboardHelper.SetClipboardData(surface.LastSaveFullPath); + + private void CopyPathMenuItemClick(object sender, EventArgs e) { + ClipboardHelper.SetClipboardData(_surface.LastSaveFullPath); } - - void OpenDirectoryMenuItemClick(object sender, EventArgs e) { - ProcessStartInfo psi = new ProcessStartInfo("explorer"); - psi.Arguments = Path.GetDirectoryName(surface.LastSaveFullPath); - psi.UseShellExecute = false; + + private void OpenDirectoryMenuItemClick(object sender, EventArgs e) { + ProcessStartInfo psi = new ProcessStartInfo("explorer") + { + Arguments = Path.GetDirectoryName(_surface.LastSaveFullPath), + UseShellExecute = false + }; using (Process p = new Process()) { p.StartInfo = psi; p.Start(); @@ -984,33 +1001,33 @@ namespace Greenshot { } #endregion - private void bindFieldControls() { - new BidirectionalBinding(btnFillColor, "SelectedColor", surface.FieldAggregator.GetField(FieldType.FILL_COLOR), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(btnLineColor, "SelectedColor", surface.FieldAggregator.GetField(FieldType.LINE_COLOR), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(lineThicknessUpDown, "Value", surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(blurRadiusUpDown, "Value", surface.FieldAggregator.GetField(FieldType.BLUR_RADIUS), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(magnificationFactorUpDown, "Value", surface.FieldAggregator.GetField(FieldType.MAGNIFICATION_FACTOR), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(pixelSizeUpDown, "Value", surface.FieldAggregator.GetField(FieldType.PIXEL_SIZE), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(brightnessUpDown, "Value", surface.FieldAggregator.GetField(FieldType.BRIGHTNESS), "Value", DecimalDoublePercentageConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(fontFamilyComboBox, "Text", surface.FieldAggregator.GetField(FieldType.FONT_FAMILY), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(fontSizeUpDown, "Value", surface.FieldAggregator.GetField(FieldType.FONT_SIZE), "Value", DecimalFloatConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(fontBoldButton, "Checked", surface.FieldAggregator.GetField(FieldType.FONT_BOLD), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(fontItalicButton, "Checked", surface.FieldAggregator.GetField(FieldType.FONT_ITALIC), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(textHorizontalAlignmentButton, "SelectedTag", surface.FieldAggregator.GetField(FieldType.TEXT_HORIZONTAL_ALIGNMENT), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(textVerticalAlignmentButton, "SelectedTag", surface.FieldAggregator.GetField(FieldType.TEXT_VERTICAL_ALIGNMENT), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(shadowButton, "Checked", surface.FieldAggregator.GetField(FieldType.SHADOW), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(previewQualityUpDown, "Value", surface.FieldAggregator.GetField(FieldType.PREVIEW_QUALITY), "Value", DecimalDoublePercentageConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(obfuscateModeButton, "SelectedTag", surface.FieldAggregator.GetField(FieldType.PREPARED_FILTER_OBFUSCATE), "Value"); - new BidirectionalBinding(highlightModeButton, "SelectedTag", surface.FieldAggregator.GetField(FieldType.PREPARED_FILTER_HIGHLIGHT), "Value"); + private void BindFieldControls() { + new BidirectionalBinding(btnFillColor, "SelectedColor", _surface.FieldAggregator.GetField(FieldType.FILL_COLOR), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(btnLineColor, "SelectedColor", _surface.FieldAggregator.GetField(FieldType.LINE_COLOR), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(lineThicknessUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(blurRadiusUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.BLUR_RADIUS), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(magnificationFactorUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.MAGNIFICATION_FACTOR), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(pixelSizeUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.PIXEL_SIZE), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(brightnessUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.BRIGHTNESS), "Value", DecimalDoublePercentageConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(fontFamilyComboBox, "Text", _surface.FieldAggregator.GetField(FieldType.FONT_FAMILY), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(fontSizeUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.FONT_SIZE), "Value", DecimalFloatConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(fontBoldButton, "Checked", _surface.FieldAggregator.GetField(FieldType.FONT_BOLD), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(fontItalicButton, "Checked", _surface.FieldAggregator.GetField(FieldType.FONT_ITALIC), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(textHorizontalAlignmentButton, "SelectedTag", _surface.FieldAggregator.GetField(FieldType.TEXT_HORIZONTAL_ALIGNMENT), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(textVerticalAlignmentButton, "SelectedTag", _surface.FieldAggregator.GetField(FieldType.TEXT_VERTICAL_ALIGNMENT), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(shadowButton, "Checked", _surface.FieldAggregator.GetField(FieldType.SHADOW), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(previewQualityUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.PREVIEW_QUALITY), "Value", DecimalDoublePercentageConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(obfuscateModeButton, "SelectedTag", _surface.FieldAggregator.GetField(FieldType.PREPARED_FILTER_OBFUSCATE), "Value"); + new BidirectionalBinding(highlightModeButton, "SelectedTag", _surface.FieldAggregator.GetField(FieldType.PREPARED_FILTER_HIGHLIGHT), "Value"); } /// /// shows/hides field controls (2nd toolbar on top) depending on fields of selected elements /// - private void refreshFieldControls() { + private void RefreshFieldControls() { propertiesToolStrip.SuspendLayout(); - if(surface.HasSelectedElements || surface.DrawingMode != DrawingModes.None) { - FieldAggregator props = surface.FieldAggregator; + if(_surface.HasSelectedElements || _surface.DrawingMode != DrawingModes.None) { + FieldAggregator props = _surface.FieldAggregator; btnFillColor.Visible = props.HasFieldValue(FieldType.FILL_COLOR); btnLineColor.Visible = props.HasFieldValue(FieldType.LINE_COLOR); lineThicknessLabel.Visible = lineThicknessUpDown.Visible = props.HasFieldValue(FieldType.LINE_THICKNESS); @@ -1033,12 +1050,12 @@ namespace Greenshot { obfuscateModeButton.Visible = props.HasFieldValue(FieldType.PREPARED_FILTER_OBFUSCATE); highlightModeButton.Visible = props.HasFieldValue(FieldType.PREPARED_FILTER_HIGHLIGHT); } else { - hideToolstripItems(); + HideToolstripItems(); } propertiesToolStrip.ResumeLayout(); } - private void hideToolstripItems() { + private void HideToolstripItems() { foreach(ToolStripItem toolStripItem in propertiesToolStrip.Items) { toolStripItem.Visible = false; } @@ -1047,23 +1064,23 @@ namespace Greenshot { /// /// refreshes all editor controls depending on selected elements and their fields /// - private void refreshEditorControls() { - int stepLabels = surface.CountStepLabels(null); + private void RefreshEditorControls() { + int stepLabels = _surface.CountStepLabels(null); Image icon; if (stepLabels <= 20) { - icon = ((System.Drawing.Image)(resources.GetObject(string.Format("btnStepLabel{0:00}.Image", stepLabels)))); + icon = (Image)resources.GetObject(string.Format("btnStepLabel{0:00}.Image", stepLabels)); } else { - icon = ((System.Drawing.Image)(resources.GetObject("btnStepLabel20+.Image"))); + icon = (Image)resources.GetObject("btnStepLabel20+.Image"); } - this.btnStepLabel.Image = icon; - this.addCounterToolStripMenuItem.Image = icon; + btnStepLabel.Image = icon; + addCounterToolStripMenuItem.Image = icon; - FieldAggregator props = surface.FieldAggregator; + FieldAggregator props = _surface.FieldAggregator; // if a confirmable element is selected, we must disable most of the controls // since we demand confirmation or cancel for confirmable element if (props.HasFieldValue(FieldType.FLAGS) && ((FieldType.Flag)props.GetFieldValue(FieldType.FLAGS) & FieldType.Flag.CONFIRMABLE) == FieldType.Flag.CONFIRMABLE) { // disable most controls - if(!controlsDisabledDueToConfirmable) { + if(!_controlsDisabledDueToConfirmable) { ToolStripItemEndisabler.Disable(menuStrip1); ToolStripItemEndisabler.Disable(destinationsToolStrip); ToolStripItemEndisabler.Disable(toolsToolStrip); @@ -1071,25 +1088,25 @@ namespace Greenshot { ToolStripItemEndisabler.Enable(helpToolStripMenuItem); ToolStripItemEndisabler.Enable(aboutToolStripMenuItem); ToolStripItemEndisabler.Enable(preferencesToolStripMenuItem); - controlsDisabledDueToConfirmable = true; + _controlsDisabledDueToConfirmable = true; } - } else if(controlsDisabledDueToConfirmable) { + } else if(_controlsDisabledDueToConfirmable) { // re-enable disabled controls, confirmable element has either been confirmed or cancelled ToolStripItemEndisabler.Enable(menuStrip1); ToolStripItemEndisabler.Enable(destinationsToolStrip); ToolStripItemEndisabler.Enable(toolsToolStrip); - controlsDisabledDueToConfirmable = false; + _controlsDisabledDueToConfirmable = false; } // en/disable controls depending on whether an element is selected at all - updateClipboardSurfaceDependencies(); - updateUndoRedoSurfaceDependencies(); + UpdateClipboardSurfaceDependencies(); + UpdateUndoRedoSurfaceDependencies(); // en/disablearrage controls depending on hierarchy of selected elements - bool actionAllowedForSelection = surface.HasSelectedElements && !controlsDisabledDueToConfirmable; - bool push = actionAllowedForSelection && surface.CanPushSelectionDown(); - bool pull = actionAllowedForSelection && surface.CanPullSelectionUp(); - arrangeToolStripMenuItem.Enabled = (push || pull); + bool actionAllowedForSelection = _surface.HasSelectedElements && !_controlsDisabledDueToConfirmable; + bool push = actionAllowedForSelection && _surface.CanPushSelectionDown(); + bool pull = actionAllowedForSelection && _surface.CanPullSelectionUp(); + arrangeToolStripMenuItem.Enabled = push || pull; if (arrangeToolStripMenuItem.Enabled) { upToTopToolStripMenuItem.Enabled = pull; upOneLevelToolStripMenuItem.Enabled = pull; @@ -1098,29 +1115,35 @@ namespace Greenshot { } // finally show/hide field controls depending on the fields of selected elements - refreshFieldControls(); - } - - - void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) { - surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; - } - - void EditToolStripMenuItemClick(object sender, EventArgs e) { - updateClipboardSurfaceDependencies(); - updateUndoRedoSurfaceDependencies(); + RefreshFieldControls(); } - void FontPropertyChanged(object sender, EventArgs e) { + + private void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) { + _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; + } + + private void EditToolStripMenuItemClick(object sender, EventArgs e) { + UpdateClipboardSurfaceDependencies(); + UpdateUndoRedoSurfaceDependencies(); + } + + private void FontPropertyChanged(object sender, EventArgs e) { // in case we forced another FontStyle before, reset it first. - if(originalBoldCheckState != fontBoldButton.Checked) fontBoldButton.Checked = originalBoldCheckState; - if(originalItalicCheckState != fontItalicButton.Checked) fontItalicButton.Checked = originalItalicCheckState; + if (fontBoldButton != null && _originalBoldCheckState != fontBoldButton.Checked) + { + fontBoldButton.Checked = _originalBoldCheckState; + } + if (fontItalicButton != null && _originalItalicCheckState != fontItalicButton.Checked) + { + fontItalicButton.Checked = _originalItalicCheckState; + } FontFamily fam = fontFamilyComboBox.FontFamily; bool boldAvailable = fam.IsStyleAvailable(FontStyle.Bold); if(!boldAvailable) { - originalBoldCheckState = fontBoldButton.Checked; + _originalBoldCheckState = fontBoldButton.Checked; fontBoldButton.Checked = false; } fontBoldButton.Enabled = boldAvailable; @@ -1137,55 +1160,56 @@ namespace Greenshot { fontItalicButton.Checked = true; } } - } - - void FieldAggregatorFieldChanged(object sender, FieldChangedEventArgs e) { + } + + private void FieldAggregatorFieldChanged(object sender, FieldChangedEventArgs e) { // in addition to selection, deselection of elements, we need to // refresh toolbar if prepared filter mode is changed if(e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) { - refreshFieldControls(); + RefreshFieldControls(); } } - - void FontBoldButtonClick(object sender, EventArgs e) { - originalBoldCheckState = fontBoldButton.Checked; + + private void FontBoldButtonClick(object sender, EventArgs e) { + _originalBoldCheckState = fontBoldButton.Checked; } - void FontItalicButtonClick(object sender, EventArgs e) { - originalItalicCheckState = fontItalicButton.Checked; + private void FontItalicButtonClick(object sender, EventArgs e) { + _originalItalicCheckState = fontItalicButton.Checked; } - - void ToolBarFocusableElementGotFocus(object sender, EventArgs e) { - surface.KeysLocked = true; + + private void ToolBarFocusableElementGotFocus(object sender, EventArgs e) { + _surface.KeysLocked = true; } - void ToolBarFocusableElementLostFocus(object sender, EventArgs e) { - surface.KeysLocked = false; + + private void ToolBarFocusableElementLostFocus(object sender, EventArgs e) { + _surface.KeysLocked = false; } - - void SaveElementsToolStripMenuItemClick(object sender, EventArgs e) { + + private void SaveElementsToolStripMenuItemClick(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Greenshot templates (*.gst)|*.gst"; - saveFileDialog.FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(coreConfiguration.OutputFileFilenamePattern, surface.CaptureDetails); + saveFileDialog.FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(coreConfiguration.OutputFileFilenamePattern, _surface.CaptureDetails); DialogResult dialogResult = saveFileDialog.ShowDialog(); if(dialogResult.Equals(DialogResult.OK)) { using (Stream streamWrite = File.OpenWrite(saveFileDialog.FileName)) { - surface.SaveElementsToStream(streamWrite); + _surface.SaveElementsToStream(streamWrite); } } } - - void LoadElementsToolStripMenuItemClick(object sender, EventArgs e) { + + private void LoadElementsToolStripMenuItemClick(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Greenshot templates (*.gst)|*.gst"; if (openFileDialog.ShowDialog() == DialogResult.OK) { using (Stream streamRead = File.OpenRead(openFileDialog.FileName)) { - surface.LoadElementsFromStream(streamRead); + _surface.LoadElementsFromStream(streamRead); } - surface.Refresh(); + _surface.Refresh(); } } - void DestinationToolStripMenuItemClick(object sender, EventArgs e) { + private void DestinationToolStripMenuItemClick(object sender, EventArgs e) { IDestination clickedDestination = null; if (sender is Control) { Control clickedControl = sender as Control; @@ -1199,39 +1223,39 @@ namespace Greenshot { clickedDestination = (IDestination)clickedMenuItem.Tag; } if (clickedDestination != null) { - ExportInformation exportInformation = clickedDestination.ExportCapture(true, surface, surface.CaptureDetails); + ExportInformation exportInformation = clickedDestination.ExportCapture(true, _surface, _surface.CaptureDetails); if (exportInformation != null && exportInformation.ExportMade) { - surface.Modified = false; + _surface.Modified = false; } } } protected void FilterPresetDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { - refreshFieldControls(); + RefreshFieldControls(); Invalidate(true); } - - void SelectAllToolStripMenuItemClick(object sender, EventArgs e) { - surface.SelectAllElements(); + + private void SelectAllToolStripMenuItemClick(object sender, EventArgs e) { + _surface.SelectAllElements(); } - - void BtnConfirmClick(object sender, EventArgs e) { - surface.ConfirmSelectedConfirmableElements(true); - refreshFieldControls(); + + private void BtnConfirmClick(object sender, EventArgs e) { + _surface.ConfirmSelectedConfirmableElements(true); + RefreshFieldControls(); } - - void BtnCancelClick(object sender, EventArgs e) { - surface.ConfirmSelectedConfirmableElements(false); - refreshFieldControls(); + + private void BtnCancelClick(object sender, EventArgs e) { + _surface.ConfirmSelectedConfirmableElements(false); + RefreshFieldControls(); } - - void Insert_window_toolstripmenuitemMouseEnter(object sender, EventArgs e) { + + private void Insert_window_toolstripmenuitemMouseEnter(object sender, EventArgs e) { ToolStripMenuItem captureWindowMenuItem = (ToolStripMenuItem)sender; MainForm.Instance.AddCaptureWindowMenuItems(captureWindowMenuItem, Contextmenu_window_Click); } - void Contextmenu_window_Click(object sender, EventArgs e) { + private void Contextmenu_window_Click(object sender, EventArgs e) { ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender; try { WindowDetails windowToCapture = (WindowDetails)clickedItem.Tag; @@ -1245,7 +1269,7 @@ namespace Greenshot { capture = CaptureHelper.CaptureWindow(windowToCapture, capture, coreConfiguration.WindowCaptureMode); if (capture != null && capture.CaptureDetails != null && capture.Image != null) { ((Bitmap)capture.Image).SetResolution(capture.CaptureDetails.DpiX, capture.CaptureDetails.DpiY); - surface.AddImageContainer((Bitmap)capture.Image, 100, 100); + _surface.AddImageContainer((Bitmap)capture.Image, 100, 100); } Activate(); WindowDetails.ToForeground(Handle); @@ -1259,15 +1283,15 @@ namespace Greenshot { } } - void AutoCropToolStripMenuItemClick(object sender, EventArgs e) { - if (surface.AutoCrop()) { - refreshFieldControls(); + private void AutoCropToolStripMenuItemClick(object sender, EventArgs e) { + if (_surface.AutoCrop()) { + RefreshFieldControls(); } } - void AddBorderToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new BorderEffect()); - updateUndoRedoSurfaceDependencies(); + private void AddBorderToolStripMenuItemClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new BorderEffect()); + UpdateUndoRedoSurfaceDependencies(); } /// @@ -1275,13 +1299,13 @@ namespace Greenshot { /// /// /// - void AddDropshadowToolStripMenuItemClick(object sender, EventArgs e) { - DropShadowEffect dropShadowEffect = editorConfiguration.DropShadowEffectSettings; + private void AddDropshadowToolStripMenuItemClick(object sender, EventArgs e) { + DropShadowEffect dropShadowEffect = EditorConfiguration.DropShadowEffectSettings; // TODO: Use the dropshadow settings form to make it possible to change the default values DialogResult result = new DropShadowSettingsForm(dropShadowEffect).ShowDialog(this); if (result == DialogResult.OK) { - surface.ApplyBitmapEffect(dropShadowEffect); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(dropShadowEffect); + UpdateUndoRedoSurfaceDependencies(); } } @@ -1290,13 +1314,13 @@ namespace Greenshot { /// /// /// - void BtnResizeClick(object sender, EventArgs e) { - ResizeEffect resizeEffect = new ResizeEffect(surface.Image.Width, surface.Image.Height, true); + private void BtnResizeClick(object sender, EventArgs e) { + ResizeEffect resizeEffect = new ResizeEffect(_surface.Image.Width, _surface.Image.Height, true); // TODO: Use the Resize SettingsForm to make it possible to change the default values DialogResult result = new ResizeSettingsForm(resizeEffect).ShowDialog(this); if (result == DialogResult.OK) { - surface.ApplyBitmapEffect(resizeEffect); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(resizeEffect); + UpdateUndoRedoSurfaceDependencies(); } } @@ -1305,39 +1329,39 @@ namespace Greenshot { /// /// /// - void TornEdgesToolStripMenuItemClick(object sender, EventArgs e) { - TornEdgeEffect tornEdgeEffect = editorConfiguration.TornEdgeEffectSettings; + private void TornEdgesToolStripMenuItemClick(object sender, EventArgs e) { + TornEdgeEffect tornEdgeEffect = EditorConfiguration.TornEdgeEffectSettings; // TODO: Use the dropshadow settings form to make it possible to change the default values DialogResult result = new TornEdgeSettingsForm(tornEdgeEffect).ShowDialog(this); if (result == DialogResult.OK) { - surface.ApplyBitmapEffect(tornEdgeEffect); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(tornEdgeEffect); + UpdateUndoRedoSurfaceDependencies(); } } - void GrayscaleToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new GrayscaleEffect()); - updateUndoRedoSurfaceDependencies(); + private void GrayscaleToolStripMenuItemClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new GrayscaleEffect()); + UpdateUndoRedoSurfaceDependencies(); } - void ClearToolStripMenuItemClick(object sender, EventArgs e) { - surface.Clear(Color.Transparent); - updateUndoRedoSurfaceDependencies(); + private void ClearToolStripMenuItemClick(object sender, EventArgs e) { + _surface.Clear(Color.Transparent); + UpdateUndoRedoSurfaceDependencies(); } - void RotateCwToolstripButtonClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new RotateEffect(90)); - updateUndoRedoSurfaceDependencies(); + private void RotateCwToolstripButtonClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new RotateEffect(90)); + UpdateUndoRedoSurfaceDependencies(); } - - void RotateCcwToolstripButtonClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new RotateEffect(270)); - updateUndoRedoSurfaceDependencies(); + + private void RotateCcwToolstripButtonClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new RotateEffect(270)); + UpdateUndoRedoSurfaceDependencies(); } - - void InvertToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new InvertEffect()); - updateUndoRedoSurfaceDependencies(); + + private void InvertToolStripMenuItemClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new InvertEffect()); + UpdateUndoRedoSurfaceDependencies(); } private void ImageEditorFormResize(object sender, EventArgs e) { @@ -1347,25 +1371,25 @@ namespace Greenshot { Size imageSize = Surface.Image.Size; Size currentClientSize = panel1.ClientSize; var canvas = Surface as Control; + if (canvas == null) + { + return; + } Panel panel = (Panel)canvas.Parent; if (panel == null) { return; } int offsetX = -panel.HorizontalScroll.Value; int offsetY = -panel.VerticalScroll.Value; - if (canvas != null) { - if (currentClientSize.Width > imageSize.Width) { - canvas.Left = offsetX + ((currentClientSize.Width - imageSize.Width) / 2); - } else { - canvas.Left = offsetX + 0; - } + if (currentClientSize.Width > imageSize.Width) { + canvas.Left = offsetX + (currentClientSize.Width - imageSize.Width) / 2; + } else { + canvas.Left = offsetX + 0; } - if (canvas != null) { - if (currentClientSize.Height > imageSize.Height) { - canvas.Top = offsetY + ((currentClientSize.Height - imageSize.Height) / 2); - } else { - canvas.Top = offsetY + 0; - } + if (currentClientSize.Height > imageSize.Height) { + canvas.Top = offsetY + (currentClientSize.Height - imageSize.Height) / 2; + } else { + canvas.Top = offsetY + 0; } } } diff --git a/Greenshot/Forms/LanguageDialog.cs b/Greenshot/Forms/LanguageDialog.cs index ee0fb7549..4de13156a 100644 --- a/Greenshot/Forms/LanguageDialog.cs +++ b/Greenshot/Forms/LanguageDialog.cs @@ -29,9 +29,9 @@ namespace Greenshot.Forms { /// Description of LanguageDialog. /// public partial class LanguageDialog : Form { - private static ILog LOG = LogManager.GetLogger(typeof(LanguageDialog)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(LanguageDialog)); private static LanguageDialog uniqueInstance; - private bool properOkPressed = false; + private bool properOkPressed; private LanguageDialog() { // diff --git a/Greenshot/Forms/MainForm.cs b/Greenshot/Forms/MainForm.cs index e58af6640..686f507d4 100644 --- a/Greenshot/Forms/MainForm.cs +++ b/Greenshot/Forms/MainForm.cs @@ -54,7 +54,7 @@ namespace Greenshot { private static ILog LOG; private static Mutex _applicationMutex; private static CoreConfiguration _conf; - public static string LogFileLocation = null; + public static string LogFileLocation; public static void Start(string[] args) { bool isAlreadyRunning = false; @@ -258,7 +258,7 @@ namespace Greenshot { using (Form dummyForm = new Form()) { dummyForm.Icon = GreenshotResources.getGreenshotIcon(); dummyForm.ShowInTaskbar = true; - dummyForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + dummyForm.FormBorderStyle = FormBorderStyle.None; dummyForm.Location = new Point(int.MinValue, int.MinValue); dummyForm.Load += delegate { dummyForm.Size = Size.Empty; }; dummyForm.Show(); @@ -581,7 +581,7 @@ namespace Greenshot { contextMenu.ImageScalingSize = coreConfiguration.IconSize; string ieExePath = PluginUtils.GetExePath("iexplore.exe"); if (!string.IsNullOrEmpty(ieExePath)) { - this.contextmenu_captureie.Image = PluginUtils.GetCachedExeIcon(ieExePath, 0); + contextmenu_captureie.Image = PluginUtils.GetCachedExeIcon(ieExePath, 0); } } } diff --git a/Greenshot/Forms/MovableShowColorForm.cs b/Greenshot/Forms/MovableShowColorForm.cs index 6173a4b4e..3b378894a 100644 --- a/Greenshot/Forms/MovableShowColorForm.cs +++ b/Greenshot/Forms/MovableShowColorForm.cs @@ -85,8 +85,8 @@ namespace Greenshot.Forms { /// /// Point with the coordinates /// Color at the specified screenCoordinates - static private Color GetPixelColor(Point screenCoordinates) { - using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.fromDesktop()) { + private static Color GetPixelColor(Point screenCoordinates) { + using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.FromDesktop()) { try { uint pixel = GDI32.GetPixel(screenDC, screenCoordinates.X, screenCoordinates.Y); Color color = Color.FromArgb(255, (int)(pixel & 0xFF), (int)(pixel & 0xFF00) >> 8, (int)(pixel & 0xFF0000) >> 16); diff --git a/Greenshot/Forms/ResizeSettingsForm.cs b/Greenshot/Forms/ResizeSettingsForm.cs index db8cac328..84c8bd31f 100644 --- a/Greenshot/Forms/ResizeSettingsForm.cs +++ b/Greenshot/Forms/ResizeSettingsForm.cs @@ -29,9 +29,9 @@ namespace Greenshot.Forms { /// A form to set the resize settings /// public partial class ResizeSettingsForm : BaseForm { - private ResizeEffect effect; - private string value_pixel; - private string value_percent; + private readonly ResizeEffect effect; + private readonly string value_pixel; + private readonly string value_percent; private double newWidth, newHeight; public ResizeSettingsForm(ResizeEffect effect) { @@ -50,8 +50,8 @@ namespace Greenshot.Forms { textbox_height.Text = effect.Height.ToString(); newWidth = effect.Width; newHeight = effect.Height; - combobox_width.SelectedIndexChanged += new System.EventHandler(this.combobox_SelectedIndexChanged); - combobox_height.SelectedIndexChanged += new System.EventHandler(this.combobox_SelectedIndexChanged); + combobox_width.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged); + combobox_height.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged); checkbox_aspectratio.Checked = effect.MaintainAspectRatio; } @@ -82,7 +82,7 @@ namespace Greenshot.Forms { private void displayWidth() { double displayValue; if (value_percent.Equals(combobox_width.SelectedItem)) { - displayValue = ((double)newWidth / (double)effect.Width) * 100d; + displayValue = (double)newWidth / (double)effect.Width * 100d; } else { displayValue = newWidth; } @@ -92,7 +92,7 @@ namespace Greenshot.Forms { private void displayHeight() { double displayValue; if (value_percent.Equals(combobox_height.SelectedItem)) { - displayValue = ((double)newHeight / (double)effect.Height) * 100d; + displayValue = (double)newHeight / (double)effect.Height * 100d; } else { displayValue = newHeight; } @@ -126,25 +126,25 @@ namespace Greenshot.Forms { if (isWidth) { if (isPercent) { percent = double.Parse(textbox_width.Text); - newWidth = ((double)effect.Width / 100d) * percent; + newWidth = (double)effect.Width / 100d * percent; } else { newWidth = double.Parse(textbox_width.Text); - percent = ((double)double.Parse(textbox_width.Text) / (double)effect.Width) * 100d; + percent = (double)double.Parse(textbox_width.Text) / (double)effect.Width * 100d; } if (checkbox_aspectratio.Checked) { - newHeight = ((double)effect.Height / 100d) * percent; + newHeight = (double)effect.Height / 100d * percent; displayHeight(); } } else { if (isPercent) { percent = double.Parse(textbox_height.Text); - newHeight = ((double)effect.Height / 100d) * percent; + newHeight = (double)effect.Height / 100d * percent; } else { newHeight = double.Parse(textbox_height.Text); - percent = ((double)double.Parse(textbox_height.Text) / (double)effect.Height) * 100d; + percent = (double)double.Parse(textbox_height.Text) / (double)effect.Height * 100d; } if (checkbox_aspectratio.Checked) { - newWidth = ((double)effect.Width / 100d) * percent; + newWidth = (double)effect.Width / 100d * percent; displayWidth(); } } diff --git a/Greenshot/Forms/SettingsForm.cs b/Greenshot/Forms/SettingsForm.cs index b64fdfaf0..10b8cec7a 100644 --- a/Greenshot/Forms/SettingsForm.cs +++ b/Greenshot/Forms/SettingsForm.cs @@ -43,7 +43,7 @@ namespace Greenshot { /// Description of SettingsForm. /// public partial class SettingsForm : BaseForm { - private static ILog LOG = LogManager.GetLogger(typeof(SettingsForm)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(SettingsForm)); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); private readonly ToolTip _toolTip = new ToolTip(); private bool _inHotkey; @@ -237,7 +237,7 @@ namespace Greenshot { string filenamePart = pathParts[pathParts.Length-1]; settingsOk = FilenameHelper.IsFilenameValid(filenamePart); - for (int i = 0; (settingsOk && i public class ToolStripMenuSelectList : ToolStripMenuItem { - private static CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); - private bool multiCheckAllowed = false; - private bool updateInProgress = false; + private static readonly CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); + private readonly bool multiCheckAllowed; + private bool updateInProgress; private static Image defaultImage; /// diff --git a/Greenshot/Forms/TornEdgeSettingsForm.cs b/Greenshot/Forms/TornEdgeSettingsForm.cs index 63bae471a..707ea5c32 100644 --- a/Greenshot/Forms/TornEdgeSettingsForm.cs +++ b/Greenshot/Forms/TornEdgeSettingsForm.cs @@ -26,7 +26,7 @@ using GreenshotPlugin.Core; namespace Greenshot.Forms { public partial class TornEdgeSettingsForm : BaseForm { - private TornEdgeEffect effect; + private readonly TornEdgeEffect effect; public TornEdgeSettingsForm(TornEdgeEffect effect) { this.effect = effect; InitializeComponent(); @@ -60,11 +60,6 @@ namespace Greenshot.Forms { DialogResult = DialogResult.OK; } - private void ButtonReset_Click(object sender, EventArgs e) { - effect.Reset(); - ShowSettings(); - } - private void ShadowCheckbox_CheckedChanged(object sender, EventArgs e) { thickness.Enabled = shadowCheckbox.Checked; offsetX.Enabled = shadowCheckbox.Checked; diff --git a/Greenshot/Helpers/CaptureHelper.cs b/Greenshot/Helpers/CaptureHelper.cs index 301b97c14..5d3868194 100644 --- a/Greenshot/Helpers/CaptureHelper.cs +++ b/Greenshot/Helpers/CaptureHelper.cs @@ -42,7 +42,7 @@ namespace Greenshot.Helpers { /// public class CaptureHelper : IDisposable { private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); // TODO: when we get the screen capture code working correctly, this needs to be enabled //private static ScreenCaptureHelper screenCapture = null; private List _windows = new List(); @@ -404,7 +404,7 @@ namespace Greenshot.Helpers { // Set capture title, fixing bug #3569703 foreach (WindowDetails window in WindowDetails.GetVisibleWindows()) { - Point estimatedLocation = new Point(conf.LastCapturedRegion.X + (conf.LastCapturedRegion.Width / 2), conf.LastCapturedRegion.Y + (conf.LastCapturedRegion.Height / 2)); + Point estimatedLocation = new Point(conf.LastCapturedRegion.X + conf.LastCapturedRegion.Width / 2, conf.LastCapturedRegion.Y + conf.LastCapturedRegion.Height / 2); if (window.Contains(estimatedLocation)) { _selectedCaptureWindow = window; _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; @@ -850,14 +850,14 @@ namespace Greenshot.Helpers { // check if GDI capture any good, by comparing it with the screen content int blackCountGDI = ImageHelper.CountColor(tmpCapture.Image, Color.Black, false); int GDIPixels = tmpCapture.Image.Width * tmpCapture.Image.Height; - int blackPercentageGDI = (blackCountGDI * 100) / GDIPixels; + 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.CaptureRectangleFromDesktopScreen(screenCapture, windowRectangle) != null) { int blackCountScreen = ImageHelper.CountColor(screenCapture.Image, Color.Black, false); - int blackPercentageScreen = (blackCountScreen * 100) / screenPixels; + int blackPercentageScreen = blackCountScreen * 100 / screenPixels; if (screenPixels == GDIPixels) { // "easy compare", both have the same size // If GDI has more black, use the screen capture. diff --git a/Greenshot/Helpers/CopyData.cs b/Greenshot/Helpers/CopyData.cs index ab695822d..776de7a99 100644 --- a/Greenshot/Helpers/CopyData.cs +++ b/Greenshot/Helpers/CopyData.cs @@ -18,6 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + using System; using System.Collections; using System.Collections.Generic; @@ -28,21 +29,21 @@ using System.Windows.Forms; using GreenshotPlugin.Core; -/// -/// Code from vbAccelerator, location: -/// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows_Messages/Simple_Interprocess_Communication/WM_COPYDATA_Demo_zip_SimpleInterprocessCommunicationsCS_CopyData_cs.asp -/// namespace Greenshot.Helpers { public enum CommandEnum { OpenFile, Exit, FirstLaunch, ReloadConfig }; + /// + /// Code from vbAccelerator, location: + /// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows_Messages/Simple_Interprocess_Communication/WM_COPYDATA_Demo_zip_SimpleInterprocessCommunicationsCS_CopyData_cs.asp + /// [Serializable()] public class CopyDataTransport { - List> commands; + private readonly List> _commands; public List> Commands { - get {return commands;} + get {return _commands;} } public CopyDataTransport() { - commands = new List>(); + _commands = new List>(); } public CopyDataTransport(CommandEnum command) : this() { @@ -53,10 +54,10 @@ namespace Greenshot.Helpers { AddCommand(command, commandData); } public void AddCommand(CommandEnum command) { - commands.Add(new KeyValuePair(command, null)); + _commands.Add(new KeyValuePair(command, null)); } public void AddCommand(CommandEnum command, string commandData) { - commands.Add(new KeyValuePair(command, commandData)); + _commands.Add(new KeyValuePair(command, commandData)); } } @@ -81,16 +82,16 @@ namespace Greenshot.Helpers { [StructLayout(LayoutKind.Sequential)] private struct COPYDATASTRUCT { - public IntPtr dwData; - public int cbData; - public IntPtr lpData; + public readonly IntPtr dwData; + public readonly int cbData; + public readonly IntPtr lpData; } private const int WM_COPYDATA = 0x4A; private const int WM_DESTROY = 0x2; #region Member Variables - private CopyDataChannels channels = null; + private CopyDataChannels _channels; #endregion /// @@ -109,7 +110,7 @@ namespace Greenshot.Helpers { BinaryFormatter b = new BinaryFormatter(); CopyDataObjectData cdo = (CopyDataObjectData) b.Deserialize(stream); - if (channels != null && channels.Contains(cdo.Channel)) { + if (_channels != null && _channels.Contains(cdo.Channel)) { CopyDataReceivedEventArgs d = new CopyDataReceivedEventArgs(cdo.Channel, cdo.Data, cdo.Sent); OnCopyDataReceived(d); m.Result = (IntPtr) 1; @@ -119,8 +120,8 @@ namespace Greenshot.Helpers { // WM_DESTROY fires before OnHandleChanged and is // a better place to ensure that we've cleared // everything up. - if (channels != null) { - channels.OnHandleChange(); + if (_channels != null) { + _channels.OnHandleChange(); } base.OnHandleChange(); } @@ -131,8 +132,12 @@ namespace Greenshot.Helpers { /// Raises the DataReceived event from this class. /// /// The data which has been received. - protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) { - CopyDataReceived(this, e); + protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) + { + if (CopyDataReceived != null) + { + CopyDataReceived(this, e); + } } /// @@ -144,8 +149,8 @@ namespace Greenshot.Helpers { /// protected override void OnHandleChange () { // need to clear up everything we had set. - if (channels != null) { - channels.OnHandleChange(); + if (_channels != null) { + _channels.OnHandleChange(); } base.OnHandleChange(); } @@ -155,7 +160,7 @@ namespace Greenshot.Helpers { /// public CopyDataChannels Channels { get { - return channels; + return _channels; } } @@ -168,9 +173,9 @@ namespace Greenshot.Helpers { /// Clears up any resources associated with this object. /// protected virtual void Dispose(bool disposing) { - if (disposing && channels != null) { - channels.Clear(); - channels = null; + if (disposing && _channels != null) { + _channels.Clear(); + _channels = null; } } @@ -178,7 +183,7 @@ namespace Greenshot.Helpers { /// Constructs a new instance of the CopyData class /// public CopyData() { - channels = new CopyDataChannels(this); + _channels = new CopyDataChannels(this); } /// @@ -196,45 +201,28 @@ namespace Greenshot.Helpers { /// which has been sent from another application. /// public class CopyDataReceivedEventArgs : EventArgs { - private string channelName = ""; - private object data = null; - private DateTime sent; - private DateTime received; - /// /// Gets the channel name that this data was sent on. /// - public string ChannelName { - get { - return channelName; - } - } + public string ChannelName { get; } = ""; + /// /// Gets the data object which was sent. /// - public Object Data { - get { - return data; - } - } + public object Data { get; } + /// /// Gets the date and time which at the data was sent /// by the sending application. /// - public DateTime Sent { - get { - return sent; - } - } + public DateTime Sent { get; } + /// /// Gets the date and time which this data item as /// received. /// - public DateTime Received { - get { - return received; - } - } + public DateTime Received { get; } + /// /// Constructs an instance of this class. /// @@ -242,10 +230,10 @@ namespace Greenshot.Helpers { /// The data which was sent /// The date and time the data was sent internal CopyDataReceivedEventArgs(string channelName, object data, DateTime sent) { - this.channelName = channelName; - this.data = data; - this.sent = sent; - received = DateTime.Now; + ChannelName = channelName; + Data = data; + Sent = sent; + Received = DateTime.Now; } } @@ -254,7 +242,7 @@ namespace Greenshot.Helpers { /// class. /// public class CopyDataChannels : DictionaryBase { - private NativeWindow owner = null; + private readonly NativeWindow _owner; /// /// Returns an enumerator for each of the CopyDataChannel objects @@ -296,7 +284,7 @@ namespace Greenshot.Helpers { /// receive messages. /// public void Add(string channelName) { - CopyDataChannel cdc = new CopyDataChannel(owner, channelName); + CopyDataChannel cdc = new CopyDataChannel(_owner, channelName); Dictionary.Add(channelName , cdc); } /// @@ -334,7 +322,7 @@ namespace Greenshot.Helpers { /// just been removed protected override void OnRemoveComplete ( Object key , Object data ) { ( (CopyDataChannel) data).Dispose(); - base.OnRemove(key, data); + OnRemove(key, data); } /// @@ -357,7 +345,7 @@ namespace Greenshot.Helpers { /// The NativeWindow this collection /// will be associated with internal CopyDataChannels(NativeWindow owner) { - this.owner = owner; + _owner = owner; } } @@ -367,14 +355,14 @@ namespace Greenshot.Helpers { public class CopyDataChannel : IDisposable { #region Unmanaged Code [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static IntPtr GetProp(IntPtr hwnd, string lpString); + private static extern IntPtr GetProp(IntPtr hwnd, string lpString); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static bool SetProp(IntPtr hwnd, string lpString, IntPtr hData); + private static extern bool SetProp(IntPtr hwnd, string lpString, IntPtr hData); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static IntPtr RemoveProp(IntPtr hwnd, string lpString); + private static extern IntPtr RemoveProp(IntPtr hwnd, string lpString); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam); + private static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam); [StructLayout(LayoutKind.Sequential)] private struct COPYDATASTRUCT { @@ -387,19 +375,15 @@ namespace Greenshot.Helpers { #endregion #region Member Variables - private string channelName = ""; - private NativeWindow owner = null; - private bool recreateChannel = false; + + private readonly NativeWindow _owner; + private bool _recreateChannel; #endregion /// /// Gets the name associated with this channel. /// - public string ChannelName { - get { - return channelName; - } - } + public string ChannelName { get; private set; } /// /// Sends the specified object on this channel to any other @@ -411,12 +395,12 @@ namespace Greenshot.Helpers { public int Send(object obj) { int recipients = 0; - if (recreateChannel) { + if (_recreateChannel) { // handle has changed - addChannel(); + AddChannel(); } - CopyDataObjectData cdo = new CopyDataObjectData(obj, channelName); + CopyDataObjectData cdo = new CopyDataObjectData(obj, ChannelName); // Try to do a binary serialization on obj. @@ -446,14 +430,16 @@ namespace Greenshot.Helpers { // Send the data to each window identified on // the channel: foreach(WindowDetails window in WindowDetails.GetAllWindows()) { - if (!window.Handle.Equals(owner.Handle)) { - if (GetProp(window.Handle, channelName) != IntPtr.Zero) { - COPYDATASTRUCT cds = new COPYDATASTRUCT(); - cds.cbData = dataSize; - cds.dwData = IntPtr.Zero; - cds.lpData = ptrData; - SendMessage(window.Handle, WM_COPYDATA, owner.Handle, ref cds); - recipients += (Marshal.GetLastWin32Error() == 0 ? 1 : 0); + if (!window.Handle.Equals(_owner.Handle)) { + if (GetProp(window.Handle, ChannelName) != IntPtr.Zero) { + COPYDATASTRUCT cds = new COPYDATASTRUCT + { + cbData = dataSize, + dwData = IntPtr.Zero, + lpData = ptrData + }; + SendMessage(window.Handle, WM_COPYDATA, _owner.Handle, ref cds); + recipients += Marshal.GetLastWin32Error() == 0 ? 1 : 0; } } } @@ -466,14 +452,14 @@ namespace Greenshot.Helpers { return recipients; } - private void addChannel() { + private void AddChannel() { // Tag this window with property "channelName" - SetProp(owner.Handle, channelName, owner.Handle); + SetProp(_owner.Handle, ChannelName, _owner.Handle); } - private void removeChannel() { + private void RemoveChannel() { // Remove the "channelName" property from this window - RemoveProp(owner.Handle, channelName); + RemoveProp(_owner.Handle, ChannelName); } /// @@ -484,8 +470,8 @@ namespace Greenshot.Helpers { /// the new handle has been assigned. /// public void OnHandleChange() { - removeChannel(); - recreateChannel = true; + RemoveChannel(); + _recreateChannel = true; } public void Dispose() { @@ -498,10 +484,10 @@ namespace Greenshot.Helpers { /// protected virtual void Dispose(bool disposing) { if (disposing) { - if (channelName.Length > 0) { - removeChannel(); + if (ChannelName.Length > 0) { + RemoveChannel(); } - channelName = ""; + ChannelName = ""; } } @@ -513,9 +499,9 @@ namespace Greenshot.Helpers { /// The name of the channel to /// send messages on internal CopyDataChannel(NativeWindow owner, string channelName) { - this.owner = owner; - this.channelName = channelName; - addChannel(); + _owner = owner; + ChannelName = channelName; + AddChannel(); } ~CopyDataChannel() { @@ -552,7 +538,7 @@ namespace Greenshot.Helpers { Data = data; if (!data.GetType().IsSerializable) { throw new ArgumentException("Data object must be serializable.", - "data"); + nameof(data)); } Channel = channel; Sent = DateTime.Now; diff --git a/Greenshot/Helpers/DestinationHelper.cs b/Greenshot/Helpers/DestinationHelper.cs index 5d69c99d3..fd5f35095 100644 --- a/Greenshot/Helpers/DestinationHelper.cs +++ b/Greenshot/Helpers/DestinationHelper.cs @@ -31,9 +31,9 @@ namespace Greenshot.Helpers { /// Description of DestinationHelper. /// public static class DestinationHelper { - private static ILog LOG = LogManager.GetLogger(typeof(DestinationHelper)); - private static Dictionary RegisteredDestinations = new Dictionary(); - private static CoreConfiguration coreConfig = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(DestinationHelper)); + private static readonly Dictionary RegisteredDestinations = new Dictionary(); + private static readonly CoreConfiguration coreConfig = IniConfig.GetIniSection(); /// Initialize the destinations static DestinationHelper() { diff --git a/Greenshot/Helpers/EnvironmentInfo.cs b/Greenshot/Helpers/EnvironmentInfo.cs index 4aa2e9bf7..1da8b4e55 100644 --- a/Greenshot/Helpers/EnvironmentInfo.cs +++ b/Greenshot/Helpers/EnvironmentInfo.cs @@ -20,14 +20,12 @@ */ using System; -using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using Greenshot.IniFile; using GreenshotPlugin.UnmanagedHelpers; -using log4net; namespace Greenshot.Helpers { @@ -36,19 +34,18 @@ namespace Greenshot.Helpers /// public static class EnvironmentInfo { - private static readonly ILog LOG = LogManager.GetLogger(typeof(EnvironmentInfo)); - private static bool? isWindows = null; + private static bool? _isWindows; public static bool IsWindows { get { - if (isWindows.HasValue) + if (_isWindows.HasValue) { - return isWindows.Value; + return _isWindows.Value; } - isWindows = Environment.OSVersion.Platform.ToString().StartsWith("Win"); - return isWindows.Value; + _isWindows = Environment.OSVersion.Platform.ToString().StartsWith("Win"); + return _isWindows.Value; } } @@ -101,7 +98,7 @@ namespace Greenshot.Helpers { environment.Append(", "); } - environment.Append(String.Format("OS: {0} {1} {2} (x{3}) {4}", OSInfo.Name, OSInfo.Edition, OSInfo.ServicePack, OSInfo.Bits, OSInfo.VersionString)); + environment.Append(string.Format("OS: {0} {1} {2} (x{3}) {4}", OSInfo.Name, OSInfo.Edition, OSInfo.ServicePack, OSInfo.Bits, OSInfo.VersionString)); if (newline) { environment.AppendLine(); @@ -201,11 +198,6 @@ namespace Greenshot.Helpers exceptionText.AppendLine(EnvironmentToString(true)); exceptionText.AppendLine(ExceptionToString(exception)); exceptionText.AppendLine("Configuration dump:"); - using (TextWriter writer = new StringWriter(exceptionText)) - { - // TODO: Create summary of properties - //var iniConfig = IniConfig.Current.WriteToStreamAsync(); - } return exceptionText.ToString(); } @@ -215,13 +207,13 @@ namespace Greenshot.Helpers /// Provides detailed information about the host operating system. /// Code is available at: http://www.csharp411.com/determine-windows-version-and-edition-with-c/ /// - static public class OSInfo + public static class OSInfo { #region BITS /// /// Determines if the current application is 32 or 64-bit. /// - static public int Bits + public static int Bits { get { @@ -231,24 +223,26 @@ namespace Greenshot.Helpers #endregion BITS #region EDITION - static private string s_Edition; + private static string _sEdition; /// /// Gets the edition of the operating system running on this computer. /// - static public string Edition + public static string Edition { get { - if (s_Edition != null) + if (_sEdition != null) { - return s_Edition; //***** RETURN *****// + return _sEdition; //***** RETURN *****// } - string edition = String.Empty; + string edition = string.Empty; OperatingSystem osVersion = Environment.OSVersion; - OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX(); - osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)); + OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX + { + dwOSVersionInfoSize = Marshal.SizeOf(typeof (OSVERSIONINFOEX)) + }; if (GetVersionEx(ref osVersionInfo)) { @@ -469,18 +463,18 @@ namespace Greenshot.Helpers #endregion VERSION 6 } - s_Edition = edition; + _sEdition = edition; return edition; } } #endregion EDITION #region NAME - static private string s_Name; + private static string s_Name; /// /// Gets the name of the operating system running on this computer. /// - static public string Name + public static string Name { get { @@ -666,17 +660,17 @@ namespace Greenshot.Helpers private struct OSVERSIONINFOEX { public int dwOSVersionInfoSize; - public int dwMajorVersion; - public int dwMinorVersion; - public int dwBuildNumber; - public int dwPlatformId; + public readonly int dwMajorVersion; + public readonly int dwMinorVersion; + public readonly int dwBuildNumber; + public readonly int dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public string szCSDVersion; - public short wServicePackMajor; - public short wServicePackMinor; - public short wSuiteMask; - public byte wProductType; - public byte wReserved; + public readonly string szCSDVersion; + public readonly short wServicePackMajor; + public readonly short wServicePackMinor; + public readonly short wSuiteMask; + public readonly byte wProductType; + public readonly byte wReserved; } #endregion OSVERSIONINFOEX @@ -724,13 +718,9 @@ namespace Greenshot.Helpers #region VERSIONS private const int VER_NT_WORKSTATION = 1; - private const int VER_NT_DOMAIN_CONTROLLER = 2; private const int VER_NT_SERVER = 3; - private const int VER_SUITE_SMALLBUSINESS = 1; private const int VER_SUITE_ENTERPRISE = 2; - private const int VER_SUITE_TERMINAL = 16; private const int VER_SUITE_DATACENTER = 128; - private const int VER_SUITE_SINGLEUSERTS = 256; private const int VER_SUITE_PERSONAL = 512; private const int VER_SUITE_BLADE = 1024; #endregion VERSIONS @@ -740,11 +730,11 @@ namespace Greenshot.Helpers /// /// Gets the service pack information of the operating system running on this computer. /// - static public string ServicePack + public static string ServicePack { get { - string servicePack = String.Empty; + string servicePack = string.Empty; OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX(); osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)); @@ -778,7 +768,7 @@ namespace Greenshot.Helpers /// /// Gets the full version string of the operating system running on this computer. /// - static public string VersionString + public static string VersionString { get { @@ -791,7 +781,7 @@ namespace Greenshot.Helpers /// /// Gets the full version of the operating system running on this computer. /// - static public Version Version + public static Version Version { get { @@ -805,7 +795,7 @@ namespace Greenshot.Helpers /// /// Gets the major version number of the operating system running on this computer. /// - static public int MajorVersion + public static int MajorVersion { get { @@ -818,7 +808,7 @@ namespace Greenshot.Helpers /// /// Gets the minor version number of the operating system running on this computer. /// - static public int MinorVersion + public static int MinorVersion { get { @@ -831,7 +821,7 @@ namespace Greenshot.Helpers /// /// Gets the revision version number of the operating system running on this computer. /// - static public int RevisionVersion + public static int RevisionVersion { get { diff --git a/Greenshot/Helpers/GeometryHelper.cs b/Greenshot/Helpers/GeometryHelper.cs index 98534a2df..ff6ec0191 100644 --- a/Greenshot/Helpers/GeometryHelper.cs +++ b/Greenshot/Helpers/GeometryHelper.cs @@ -37,9 +37,9 @@ namespace Greenshot.Helpers { //Our end result int result = 0; //Take x2-x1, then square it - double part1 = Math.Pow((x2 - x1), 2); + double part1 = Math.Pow(x2 - x1, 2); //Take y2-y1, then square it - double part2 = Math.Pow((y2 - y1), 2); + double part2 = Math.Pow(y2 - y1, 2); //Add both of the parts together double underRadical = part1 + part2; //Get the square root of the parts diff --git a/Greenshot/Helpers/IECaptureHelper.cs b/Greenshot/Helpers/IECaptureHelper.cs index 1786106c9..78ceb3913 100644 --- a/Greenshot/Helpers/IECaptureHelper.cs +++ b/Greenshot/Helpers/IECaptureHelper.cs @@ -42,7 +42,7 @@ namespace Greenshot.Helpers { /// Many thanks to all the people who contributed here! /// public static class IECaptureHelper { - private static ILog LOG = LogManager.GetLogger(typeof(IECaptureHelper)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(IECaptureHelper)); private static readonly CoreConfiguration configuration = IniConfig.GetIniSection(); // Helper method to activate a certain IE Tab @@ -69,7 +69,7 @@ namespace Greenshot.Helpers { if (ieWindow != null) { Rectangle wholeClient = someWindow.ClientRectangle; Rectangle partClient = ieWindow.ClientRectangle; - int percentage = (int)(100*((float)(partClient.Width * partClient.Height)) / ((float)(wholeClient.Width * wholeClient.Height))); + int percentage = (int)(100*(float)(partClient.Width * partClient.Height) / (float)(wholeClient.Width * wholeClient.Height)); LOG.InfoFormat("Window {0}, ie part {1}, percentage {2}", wholeClient, partClient, percentage); if (percentage > minimumPercentage) { return true; @@ -143,7 +143,7 @@ namespace Greenshot.Helpers { } else if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(ieWindow.ClassName)) { List singleWindowText = new List(); try { - IHTMLDocument2 document2 = getHTMLDocument(ieWindow); + IHTMLDocument2 document2 = GetHtmlDocument(ieWindow); string title = document2.title; Marshal.ReleaseComObject(document2); if (string.IsNullOrEmpty(title)) { @@ -177,7 +177,7 @@ namespace Greenshot.Helpers { /// /// /// - private static IHTMLDocument2 getHTMLDocument(WindowDetails mainWindow) { + private static IHTMLDocument2 GetHtmlDocument(WindowDetails mainWindow) { WindowDetails ieServer; if ("Internet Explorer_Server".Equals(mainWindow.ClassName)) { ieServer = mainWindow; @@ -249,7 +249,7 @@ namespace Greenshot.Helpers { try { // Get the Document - IHTMLDocument2 document2 = getHTMLDocument(ieWindow); + IHTMLDocument2 document2 = GetHtmlDocument(ieWindow); if (document2 == null) { continue; } @@ -371,7 +371,7 @@ namespace Greenshot.Helpers { Bitmap returnBitmap = null; try { Size pageSize = PrepareCapture(documentContainer, capture); - returnBitmap = capturePage(documentContainer, capture, pageSize); + returnBitmap = CapturePage(documentContainer, pageSize); } catch (Exception captureException) { LOG.Error("Exception found, ignoring and returning nothing! Error was: ", captureException); } @@ -554,8 +554,9 @@ namespace Greenshot.Helpers { /// Capture the actual page (document) /// /// The document wrapped in a container + /// /// Bitmap with the page content as an image - private static Bitmap capturePage(DocumentContainer documentContainer, ICapture capture, Size pageSize) { + private static Bitmap CapturePage(DocumentContainer documentContainer, Size pageSize) { WindowDetails contentWindowDetails = documentContainer.ContentWindow; //Create a target bitmap to draw into with the calculated page size @@ -567,7 +568,7 @@ namespace Greenshot.Helpers { graphicsTarget.Clear(clearColor); // Get the base document & draw it - drawDocument(documentContainer, contentWindowDetails, graphicsTarget); + DrawDocument(documentContainer, contentWindowDetails, graphicsTarget); // Loop over the frames and clear their source area so we don't see any artefacts foreach(DocumentContainer frameDocument in documentContainer.Frames) { @@ -577,7 +578,7 @@ namespace Greenshot.Helpers { } // Loop over the frames and capture their content foreach(DocumentContainer frameDocument in documentContainer.Frames) { - drawDocument(frameDocument, contentWindowDetails, graphicsTarget); + DrawDocument(frameDocument, contentWindowDetails, graphicsTarget); } } return returnBitmap; @@ -586,11 +587,11 @@ namespace Greenshot.Helpers { /// /// This method takes the actual capture of the document (frame) /// - /// + /// /// Needed for referencing the location of the frame /// Bitmap with the capture - private static void drawDocument(DocumentContainer documentContainer, WindowDetails contentWindowDetails, Graphics graphicsTarget) { - documentContainer.setAttribute("scroll", 1); + private static void DrawDocument(DocumentContainer documentContainer, WindowDetails contentWindowDetails, Graphics graphicsTarget) { + documentContainer.SetAttribute("scroll", 1); //Get Browser Window Width & Height int pageWidth = documentContainer.ScrollWidth; @@ -621,14 +622,14 @@ namespace Greenshot.Helpers { Point targetOffset = new Point(); // Loop of the pages and make a copy of the visible viewport - while ((horizontalPage * viewportWidth) < pageWidth) { + while (horizontalPage * viewportWidth < pageWidth) { // Scroll to location documentContainer.ScrollLeft = viewportWidth * horizontalPage; targetOffset.X = documentContainer.ScrollLeft; // Variable used for looping vertically int verticalPage = 0; - while ((verticalPage * viewportHeight) < pageHeight) { + while (verticalPage * viewportHeight < pageHeight) { // Scroll to location documentContainer.ScrollTop = viewportHeight * verticalPage; //Shoot visible window diff --git a/Greenshot/Helpers/IEInterop/IEContainer.cs b/Greenshot/Helpers/IEInterop/IEContainer.cs index 0b5b740bc..899ebae46 100644 --- a/Greenshot/Helpers/IEInterop/IEContainer.cs +++ b/Greenshot/Helpers/IEInterop/IEContainer.cs @@ -26,33 +26,31 @@ using System.Runtime.InteropServices; using GreenshotPlugin.Core; using Greenshot.Interop.IE; -using Greenshot.IniFile; using log4net; using IServiceProvider = Greenshot.Interop.IServiceProvider; namespace Greenshot.Helpers.IEInterop { public class DocumentContainer { - private static ILog LOG = LogManager.GetLogger(typeof(DocumentContainer)); - private static CoreConfiguration configuration = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(DocumentContainer)); private const int E_ACCESSDENIED = unchecked((int)0x80070005L); private static readonly Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046"); private static readonly Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"); - private static int counter = 0; - private int id = counter++; - private IHTMLDocument2 document2; - private IHTMLDocument3 document3; - private Point sourceLocation; - private Point destinationLocation; - private Point startLocation = Point.Empty; - private Rectangle viewportRectangle = Rectangle.Empty; - private string name = null; - private string url; - private bool isDTD; - private DocumentContainer parent; - private WindowDetails contentWindow; - private double zoomLevelX = 1; - private double zoomLevelY = 1; - private List frames = new List(); + private static int _counter; + private readonly int _id = _counter++; + private IHTMLDocument2 _document2; + private IHTMLDocument3 _document3; + private Point _sourceLocation; + private Point _destinationLocation; + private Point _startLocation = Point.Empty; + private Rectangle _viewportRectangle = Rectangle.Empty; + private string _name; + private string _url; + private bool _isDtd; + private DocumentContainer _parent; + private WindowDetails _contentWindow; + private double _zoomLevelX = 1; + private double _zoomLevelY = 1; + private readonly IList _frames = new List(); private DocumentContainer(IHTMLWindow2 frameWindow, WindowDetails contentWindow, DocumentContainer parent) { //IWebBrowser2 webBrowser2 = frame as IWebBrowser2; @@ -60,22 +58,22 @@ namespace Greenshot.Helpers.IEInterop { IHTMLDocument2 document2 = GetDocumentFromWindow(frameWindow); try { LOG.DebugFormat("frameWindow.name {0}", frameWindow.name); - name = frameWindow.name; + _name = frameWindow.name; } catch { - + // Ignore } try { LOG.DebugFormat("document2.url {0}",document2.url); } catch { - + // Ignore } try { LOG.DebugFormat("document2.title {0}", document2.title); } catch { - + // Ignore } - this.parent = parent; + _parent = parent; // Calculate startLocation for the frames IHTMLWindow2 window2 = document2.parentWindow; IHTMLWindow3 window3 = (IHTMLWindow3)window2; @@ -87,13 +85,13 @@ namespace Greenshot.Helpers.IEInterop { releaseCom(window2); releaseCom(window3); - startLocation = new Point(x, y); + _startLocation = new Point(x, y); Init(document2, contentWindow); } public DocumentContainer(IHTMLDocument2 document2, WindowDetails contentWindow) { Init(document2, contentWindow); - LOG.DebugFormat("Creating DocumentContainer for Document {0} found in window with rectangle {1}", name, SourceRectangle); + LOG.DebugFormat("Creating DocumentContainer for Document {0} found in window with rectangle {1}", _name, SourceRectangle); } /// @@ -112,17 +110,17 @@ namespace Greenshot.Helpers.IEInterop { /// IHTMLDocument2 /// WindowDetails private void Init(IHTMLDocument2 document2, WindowDetails contentWindow) { - this.document2 = document2; - this.contentWindow = contentWindow; - document3 = document2 as IHTMLDocument3; + _document2 = document2; + _contentWindow = contentWindow; + _document3 = document2 as IHTMLDocument3; // Check what access method is needed for the document IHTMLDocument5 document5 = (IHTMLDocument5)document2; //compatibility mode affects how height is computed - isDTD = false; + _isDtd = false; try { - if ((document3.documentElement != null) && (!document5.compatMode.Equals("BackCompat"))) { - isDTD = true; + if (_document3 != null && (_document3.documentElement != null) && !document5.compatMode.Equals("BackCompat")) { + _isDtd = true; } } catch (Exception ex) { LOG.Error("Error checking the compatibility mode:"); @@ -133,21 +131,21 @@ namespace Greenshot.Helpers.IEInterop { Rectangle clientRectangle = contentWindow.WindowRectangle; try { - IHTMLWindow2 window2 = (IHTMLWindow2)document2.parentWindow; + IHTMLWindow2 window2 = document2.parentWindow; //IHTMLWindow3 window3 = (IHTMLWindow3)document2.parentWindow; IHTMLScreen screen = window2.screen; IHTMLScreen2 screen2 = (IHTMLScreen2)screen; - if (parent != null) { + if (_parent != null) { // Copy parent values - zoomLevelX = parent.zoomLevelX; - zoomLevelY = parent.zoomLevelY; - viewportRectangle = parent.viewportRectangle; + _zoomLevelX = _parent._zoomLevelX; + _zoomLevelY = _parent._zoomLevelY; + _viewportRectangle = _parent._viewportRectangle; } else { //DisableScrollbars(document2); // Calculate zoom level - zoomLevelX = (double)screen2.deviceXDPI/(double)screen2.logicalXDPI; - zoomLevelY = (double)screen2.deviceYDPI/(double)screen2.logicalYDPI; + _zoomLevelX = screen2.deviceXDPI/(double)screen2.logicalXDPI; + _zoomLevelY = screen2.deviceYDPI/(double)screen2.logicalYDPI; // Calculate the viewport rectangle, needed if there is a frame around the html window @@ -162,11 +160,11 @@ namespace Greenshot.Helpers.IEInterop { if ((diffX == 4 || diffX >= 20) && (diffY == 4 || diffY >= 20)) { Point viewportOffset = new Point(2, 2); Size viewportSize = new Size(ClientWidth, ClientHeight); - viewportRectangle = new Rectangle(viewportOffset, viewportSize); - LOG.DebugFormat("viewportRect {0}", viewportRectangle); + _viewportRectangle = new Rectangle(viewportOffset, viewportSize); + LOG.DebugFormat("viewportRect {0}", _viewportRectangle); } } - LOG.DebugFormat("Zoomlevel {0}, {1}", zoomLevelX, zoomLevelY); + LOG.DebugFormat("Zoomlevel {0}, {1}", _zoomLevelX, _zoomLevelY); // Release com objects releaseCom(window2); releaseCom(screen); @@ -177,23 +175,23 @@ namespace Greenshot.Helpers.IEInterop { try { - LOG.DebugFormat("Calculated location {0} for {1}", startLocation, document2.title); - if (name == null) { - name = document2.title; + LOG.DebugFormat("Calculated location {0} for {1}", _startLocation, document2.title); + if (_name == null) { + _name = document2.title; } } catch (Exception e) { LOG.Warn("Problem while trying to get document title!", e); } try { - url = document2.url; + _url = document2.url; } catch (Exception e) { LOG.Warn("Problem while trying to get document url!", e); } - sourceLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y)); - destinationLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y)); + _sourceLocation = new Point(ScaleX(_startLocation.X), ScaleY(_startLocation.Y)); + _destinationLocation = new Point(ScaleX(_startLocation.X), ScaleY(_startLocation.Y)); - if (parent != null) { + if (_parent != null) { return; } try { @@ -203,9 +201,9 @@ namespace Greenshot.Helpers.IEInterop { IHTMLWindow2 frameWindow = frameCollection.item(frame); DocumentContainer frameData = new DocumentContainer(frameWindow, contentWindow, this); // check if frame is hidden - if (!frameData.isHidden) { - LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData.name, frameData.SourceRectangle); - frames.Add(frameData); + if (!frameData.IsHidden) { + LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData._name, frameData.SourceRectangle); + _frames.Add(frameData); } else { LOG.DebugFormat("Skipping frame {0}", frameData.Name); } @@ -223,7 +221,7 @@ namespace Greenshot.Helpers.IEInterop { try { // Correct iframe locations - foreach (IHTMLElement frameElement in document3.getElementsByTagName("IFRAME")) { + foreach (IHTMLElement frameElement in _document3.getElementsByTagName("IFRAME")) { try { CorrectFrameLocations(frameElement); // Clean up frameElement @@ -264,7 +262,7 @@ namespace Greenshot.Helpers.IEInterop { // Release IHTMLRect releaseCom(rec); LOG.DebugFormat("Looking for iframe to correct at {0}", elementBoundingLocation); - foreach(DocumentContainer foundFrame in frames) { + foreach(DocumentContainer foundFrame in _frames) { Point frameLocation = foundFrame.SourceLocation; if (frameLocation.Equals(elementBoundingLocation)) { // Match found, correcting location @@ -313,13 +311,13 @@ namespace Greenshot.Helpers.IEInterop { IServiceProvider sp = (IServiceProvider)htmlWindow; // Use IServiceProvider.QueryService to get IWebBrowser2 object. - Object brws = null; + object brws; Guid webBrowserApp = IID_IWebBrowserApp; Guid webBrowser2 = IID_IWebBrowser2; sp.QueryService(ref webBrowserApp, ref webBrowser2, out brws); // Get the document from IWebBrowser2. - IWebBrowser2 browser = (IWebBrowser2)(brws); + IWebBrowser2 browser = (IWebBrowser2)brws; return (IHTMLDocument2)browser.Document; } catch (Exception ex2) { @@ -331,9 +329,9 @@ namespace Greenshot.Helpers.IEInterop { public Color BackgroundColor { get { try { - string bgColor = (string)document2.bgColor; + string bgColor = (string)_document2.bgColor; if (bgColor != null) { - int rgbInt = Int32.Parse(bgColor.Substring(1), NumberStyles.HexNumber); + int rgbInt = int.Parse(bgColor.Substring(1), NumberStyles.HexNumber); return Color.FromArgb(rgbInt >> 16, (rgbInt >> 8) & 255, rgbInt & 255); } } catch (Exception ex) { @@ -345,46 +343,46 @@ namespace Greenshot.Helpers.IEInterop { public Rectangle ViewportRectangle { get { - return viewportRectangle; + return _viewportRectangle; } } public WindowDetails ContentWindow { get { - return contentWindow; + return _contentWindow; } } public DocumentContainer Parent { get { - return parent; + return _parent; } set { - parent = value; + _parent = value; } } private int ScaleX(int physicalValue) { - return (int)Math.Round(physicalValue * zoomLevelX, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue * _zoomLevelX, MidpointRounding.AwayFromZero); } private int ScaleY(int physicalValue) { - return (int)Math.Round(physicalValue * zoomLevelY, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue * _zoomLevelY, MidpointRounding.AwayFromZero); } private int UnscaleX(int physicalValue) { - return (int)Math.Round(physicalValue / zoomLevelX, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue / _zoomLevelX, MidpointRounding.AwayFromZero); } private int UnscaleY(int physicalValue) { - return (int)Math.Round(physicalValue / zoomLevelY, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero); } /// /// Set/change an int attribute on a document /// - public void setAttribute(string attribute, int value) { - setAttribute(attribute, value.ToString()); + public void SetAttribute(string attribute, int value) { + SetAttribute(attribute, value.ToString()); } /// @@ -392,14 +390,12 @@ namespace Greenshot.Helpers.IEInterop { /// /// Attribute to set /// Value to set - /// The IHTMLDocument2 - /// The IHTMLDocument3 - public void setAttribute(string attribute, string value) { + public void SetAttribute(string attribute, string value) { IHTMLElement element = null; - if (!isDTD) { - element = document2.body; + if (!_isDtd) { + element = _document2.body; } else { - element = document3.documentElement; + element = _document3.documentElement; } element.setAttribute(attribute, value, 1); // Release IHTMLElement com object @@ -410,18 +406,15 @@ namespace Greenshot.Helpers.IEInterop { /// Get the attribute from a document /// /// Attribute to get - /// The IHTMLDocument2 - /// The IHTMLDocument3 /// object with the attribute value - public object getAttribute(string attribute) { - IHTMLElement element = null; - object retVal = 0; - if (!isDTD) { - element = document2.body; + public object GetAttribute(string attribute) { + IHTMLElement element; + if (!_isDtd) { + element = _document2.body; } else { - element = document3.documentElement; + element = _document3.documentElement; } - retVal = element.getAttribute(attribute, 1); + var retVal = element.getAttribute(attribute, 1); // Release IHTMLElement com object releaseCom(element); return retVal; @@ -430,30 +423,30 @@ namespace Greenshot.Helpers.IEInterop { /// /// Get the attribute as int from a document /// - public int getAttributeAsInt(string attribute) { - int retVal = (int)getAttribute(attribute); + public int GetAttributeAsInt(string attribute) { + int retVal = (int)GetAttribute(attribute); return retVal; } public int ID { get { - return id; + return _id; } } public string Name { get { - return name; + return _name; } } public string Url { get { - return url; + return _url; } } - public bool isHidden { + public bool IsHidden { get { return ClientWidth == 0 || ClientHeight == 0; } @@ -461,34 +454,34 @@ namespace Greenshot.Helpers.IEInterop { public int ClientWidth { get { - return ScaleX(getAttributeAsInt("clientWidth")); + return ScaleX(GetAttributeAsInt("clientWidth")); } } public int ClientHeight { get { - return ScaleY(getAttributeAsInt("clientHeight")); + return ScaleY(GetAttributeAsInt("clientHeight")); } } public int ScrollWidth { get { - return ScaleX(getAttributeAsInt("scrollWidth")); + return ScaleX(GetAttributeAsInt("scrollWidth")); } } public int ScrollHeight { get { - return ScaleY(getAttributeAsInt("scrollHeight")); + return ScaleY(GetAttributeAsInt("scrollHeight")); } } public Point SourceLocation { get { - return sourceLocation; + return _sourceLocation; } set { - sourceLocation = value; + _sourceLocation = value; } } @@ -506,34 +499,34 @@ namespace Greenshot.Helpers.IEInterop { public int SourceLeft { get { - return sourceLocation.X; + return _sourceLocation.X; } } public int SourceTop { get { - return sourceLocation.Y; + return _sourceLocation.Y; } } public int SourceRight { get { - return sourceLocation.X + ClientWidth; + return _sourceLocation.X + ClientWidth; } } public int SourceBottom { get { - return sourceLocation.Y + ClientHeight; + return _sourceLocation.Y + ClientHeight; } } public Point DestinationLocation { get { - return destinationLocation; + return _destinationLocation; } set { - destinationLocation = value; + _destinationLocation = value; } } @@ -552,55 +545,55 @@ namespace Greenshot.Helpers.IEInterop { public int DestinationLeft { get { - return destinationLocation.X; + return _destinationLocation.X; } set { - destinationLocation.X = value; + _destinationLocation.X = value; } } public int DestinationTop { get { - return destinationLocation.Y; + return _destinationLocation.Y; } set { - destinationLocation.Y = value; + _destinationLocation.Y = value; } } public int DestinationRight { get { - return destinationLocation.X + ScrollWidth; + return _destinationLocation.X + ScrollWidth; } } public int DestinationBottom { get { - return destinationLocation.Y + ScrollHeight; + return _destinationLocation.Y + ScrollHeight; } } public int ScrollLeft { get{ - return ScaleX(getAttributeAsInt("scrollLeft")); + return ScaleX(GetAttributeAsInt("scrollLeft")); } set { - setAttribute("scrollLeft", UnscaleX(value)); + SetAttribute("scrollLeft", UnscaleX(value)); } } public int ScrollTop { get{ - return ScaleY(getAttributeAsInt("scrollTop")); + return ScaleY(GetAttributeAsInt("scrollTop")); } set { - setAttribute("scrollTop", UnscaleY(value)); + SetAttribute("scrollTop", UnscaleY(value)); } } - public List Frames { + public IList Frames { get { - return frames; + return _frames; } } } diff --git a/Greenshot/Helpers/MailHelper.cs b/Greenshot/Helpers/MailHelper.cs index 4bb549603..b7024ae0d 100644 --- a/Greenshot/Helpers/MailHelper.cs +++ b/Greenshot/Helpers/MailHelper.cs @@ -97,9 +97,9 @@ namespace Greenshot.Helpers { private class MapiFileDescriptor { public int reserved = 0; public int flags = 0; - public int position = 0; - public string path = null; - public string name = null; + public int position; + public string path; + public string name; public IntPtr type = IntPtr.Zero; } @@ -110,7 +110,8 @@ namespace Greenshot.Helpers { /// /// Specifies the valid RecipientTypes for a Recipient. /// - public enum RecipientType : int { + public enum RecipientType + { /// /// Recipient will be in the TO list. /// @@ -497,25 +498,25 @@ namespace Greenshot.Helpers { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class MapiMessage { public int Reserved = 0; - public string Subject = null; - public string NoteText = null; + public string Subject; + public string NoteText; public string MessageType = null; public string DateReceived = null; public string ConversationID = null; public int Flags = 0; public IntPtr Originator = IntPtr.Zero; - public int RecipientCount = 0; + public int RecipientCount; public IntPtr Recipients = IntPtr.Zero; - public int FileCount = 0; + public int FileCount; public IntPtr Files = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class MapiRecipDesc { public int Reserved = 0; - public int RecipientClass = 0; - public string Name = null; - public string Address = null; + public int RecipientClass; + public string Name; + public string Address; public int eIDSize = 0; public IntPtr EntryID = IntPtr.Zero; } @@ -542,12 +543,12 @@ namespace Greenshot.Helpers { /// /// The email address of this recipient. /// - public string Address = null; + public string Address; /// /// The display name of this recipient. /// - public string DisplayName = null; + public string DisplayName; /// /// How the recipient will receive this message (To, CC, BCC). diff --git a/Greenshot/Helpers/PluginHelper.cs b/Greenshot/Helpers/PluginHelper.cs index 9062490e3..c757cef68 100644 --- a/Greenshot/Helpers/PluginHelper.cs +++ b/Greenshot/Helpers/PluginHelper.cs @@ -36,12 +36,12 @@ namespace Greenshot.Helpers { [Serializable] public class PluginHelper : IGreenshotHost { private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private static string pluginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Application.ProductName); - private static string applicationPath = Path.GetDirectoryName(Application.ExecutablePath); - private static string pafPath = Path.Combine(Application.StartupPath, @"App\Greenshot"); - private static IDictionary plugins = new SortedDictionary(); + private static readonly string pluginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Application.ProductName); + private static readonly string applicationPath = Path.GetDirectoryName(Application.ExecutablePath); + private static readonly string pafPath = Path.Combine(Application.StartupPath, @"App\Greenshot"); + private static readonly IDictionary plugins = new SortedDictionary(); private static readonly PluginHelper instance = new PluginHelper(); public static PluginHelper Instance { get { @@ -66,7 +66,7 @@ namespace Greenshot.Helpers { } public bool HasPlugins() { - return (plugins != null && plugins.Count > 0); + return plugins != null && plugins.Count > 0; } public void Shutdown() { diff --git a/Greenshot/Helpers/PrintHelper.cs b/Greenshot/Helpers/PrintHelper.cs index ddb42b5b9..c9016569f 100644 --- a/Greenshot/Helpers/PrintHelper.cs +++ b/Greenshot/Helpers/PrintHelper.cs @@ -37,10 +37,10 @@ namespace Greenshot.Helpers { /// public class PrintHelper : IDisposable { private static readonly ILog LOG = LogManager.GetLogger(typeof(PrintHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private ISurface surface; - private ICaptureDetails captureDetails; + private readonly ICaptureDetails captureDetails; private PrintDocument printDocument = new PrintDocument(); private PrintDialog printDialog = new PrintDialog(); @@ -218,7 +218,7 @@ namespace Greenshot.Helpers { if (conf.OutputPrintFooter) { //printRect = new RectangleF(0, 0, printRect.Width, printRect.Height - (dateStringHeight * 2)); using (Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)) { - e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - (footerStringWidth / 2), pageRect.Height); + e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - footerStringWidth / 2, pageRect.Height); } } e.Graphics.DrawImage(image, printRect, imageRect, GraphicsUnit.Pixel); diff --git a/Greenshot/Helpers/ProcessorHelper.cs b/Greenshot/Helpers/ProcessorHelper.cs index ea5c4bef9..5da3736ac 100644 --- a/Greenshot/Helpers/ProcessorHelper.cs +++ b/Greenshot/Helpers/ProcessorHelper.cs @@ -30,8 +30,8 @@ namespace Greenshot.Helpers { /// Description of ProcessorHelper. /// public static class ProcessorHelper { - private static ILog LOG = LogManager.GetLogger(typeof(ProcessorHelper)); - private static Dictionary RegisteredProcessors = new Dictionary(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(ProcessorHelper)); + private static readonly Dictionary RegisteredProcessors = new Dictionary(); /// Initialize the Processors static ProcessorHelper() { diff --git a/Greenshot/Helpers/ScaleHelper.cs b/Greenshot/Helpers/ScaleHelper.cs index 77557fc73..7f348b932 100644 --- a/Greenshot/Helpers/ScaleHelper.cs +++ b/Greenshot/Helpers/ScaleHelper.cs @@ -22,7 +22,6 @@ using System; using System.Drawing; using System.Windows.Forms; using Greenshot.Drawing; -using log4net; namespace Greenshot.Helpers { /// @@ -45,9 +44,7 @@ namespace Greenshot.Helpers { /// Rational = 0x02 } - - private static readonly ILog LOG = LogManager.GetLogger(typeof(ScaleHelper)); - + /// /// calculates the Size an element must be resized to, in order to fit another element, keeping aspect ratio /// @@ -77,7 +74,7 @@ namespace Greenshot.Helpers { newRect.X = (targetRect.Width - currentRect.Width) / 2; break; case ContentAlignment.TopRight: - newRect.X = (targetRect.Width - currentRect.Width); + newRect.X = targetRect.Width - currentRect.Width; break; case ContentAlignment.MiddleLeft: newRect.Y = (targetRect.Height - currentRect.Height) / 2; @@ -88,18 +85,18 @@ namespace Greenshot.Helpers { break; case ContentAlignment.MiddleRight: newRect.Y = (targetRect.Height - currentRect.Height) / 2; - newRect.X = (targetRect.Width - currentRect.Width); + newRect.X = targetRect.Width - currentRect.Width; break; case ContentAlignment.BottomLeft: - newRect.Y = (targetRect.Height - currentRect.Height); + newRect.Y = targetRect.Height - currentRect.Height; break; case ContentAlignment.BottomCenter: - newRect.Y = (targetRect.Height - currentRect.Height); + newRect.Y = targetRect.Height - currentRect.Height; newRect.X = (targetRect.Width - currentRect.Width) / 2; break; case ContentAlignment.BottomRight: - newRect.Y = (targetRect.Height - currentRect.Height); - newRect.X = (targetRect.Width - currentRect.Width); + newRect.Y = targetRect.Height - currentRect.Height; + newRect.X = targetRect.Width - currentRect.Width; break; } return newRect; @@ -323,7 +320,7 @@ namespace Greenshot.Helpers { /// the current ScaleOptions depending on modifier keys held down public static ScaleOptions GetScaleOptions() { bool anchorAtCenter = (Control.ModifierKeys & Keys.Control) != 0; - bool maintainAspectRatio = ((Control.ModifierKeys & Keys.Shift) != 0); + bool maintainAspectRatio = (Control.ModifierKeys & Keys.Shift) != 0; ScaleOptions opts = ScaleOptions.Default; if(anchorAtCenter) opts |= ScaleOptions.Centered; if(maintainAspectRatio) opts |= ScaleOptions.Rational; @@ -349,7 +346,7 @@ namespace Greenshot.Helpers { } } public class FixedAngleRoundBehavior : IDoubleProcessor { - private double fixedAngle; + private readonly double fixedAngle; public FixedAngleRoundBehavior(double fixedAngle) { this.fixedAngle = fixedAngle; } diff --git a/Greenshot/Helpers/SoundHelper.cs b/Greenshot/Helpers/SoundHelper.cs index 1b84b1907..d362d8d2b 100644 --- a/Greenshot/Helpers/SoundHelper.cs +++ b/Greenshot/Helpers/SoundHelper.cs @@ -39,27 +39,27 @@ namespace Greenshot.Helpers { /// public static class SoundHelper { private static readonly ILog LOG = LogManager.GetLogger(typeof(SoundHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static GCHandle? gcHandle = null; - private static byte[] soundBuffer = null; + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static GCHandle? _gcHandle; + private static byte[] _soundBuffer; public static void Initialize() { - if (gcHandle == null) { + if (_gcHandle == null) { try { ResourceManager resources = new ResourceManager("Greenshot.Sounds", Assembly.GetExecutingAssembly()); - soundBuffer = (byte[])resources.GetObject("camera"); + _soundBuffer = (byte[])resources.GetObject("camera"); if (conf.NotificationSound != null && conf.NotificationSound.EndsWith(".wav")) { try { if (File.Exists(conf.NotificationSound)) { - soundBuffer = File.ReadAllBytes(conf.NotificationSound); + _soundBuffer = File.ReadAllBytes(conf.NotificationSound); } } catch (Exception ex) { LOG.WarnFormat("couldn't load {0}: {1}", conf.NotificationSound, ex.Message); } } // Pin sound so it can't be moved by the Garbage Collector, this was the cause for the bad sound - gcHandle = GCHandle.Alloc(soundBuffer, GCHandleType.Pinned); + _gcHandle = GCHandle.Alloc(_soundBuffer, GCHandleType.Pinned); } catch (Exception e) { LOG.Error("Error initializing.", e); } @@ -67,11 +67,11 @@ namespace Greenshot.Helpers { } public static void Play() { - if (soundBuffer != null) { + if (_soundBuffer != null) { //Thread playSoundThread = new Thread(delegate() { SoundFlags flags = SoundFlags.SND_ASYNC | SoundFlags.SND_MEMORY | SoundFlags.SND_NOWAIT | SoundFlags.SND_NOSTOP; try { - WinMM.PlaySound(gcHandle.Value.AddrOfPinnedObject(), (UIntPtr)0, (uint)flags); + WinMM.PlaySound(_gcHandle.Value.AddrOfPinnedObject(), (UIntPtr)0, (uint)flags); } catch (Exception e) { LOG.Error("Error in play.", e); } @@ -84,10 +84,10 @@ namespace Greenshot.Helpers { public static void Deinitialize() { try { - if (gcHandle != null) { + if (_gcHandle != null) { WinMM.PlaySound((byte[])null, (UIntPtr)0, (uint)0); - gcHandle.Value.Free(); - gcHandle = null; + _gcHandle.Value.Free(); + _gcHandle = null; } } catch (Exception e) { LOG.Error("Error in deinitialize.", e); diff --git a/Greenshot/Helpers/UpdateHelper.cs b/Greenshot/Helpers/UpdateHelper.cs index 723331d25..cf7437835 100644 --- a/Greenshot/Helpers/UpdateHelper.cs +++ b/Greenshot/Helpers/UpdateHelper.cs @@ -35,7 +35,7 @@ namespace Greenshot.Experimental { /// public static class UpdateHelper { private static readonly ILog LOG = LogManager.GetLogger(typeof(UpdateHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const string STABLE_DOWNLOAD_LINK = "http://getgreenshot.org/downloads/"; private const string VERSION_HISTORY_LINK = "http://getgreenshot.org/version-history/"; private static readonly object LockObject = new object(); diff --git a/Greenshot/Helpers/WindowWrapper.cs b/Greenshot/Helpers/WindowWrapper.cs index c23614482..4de8a60c1 100644 --- a/Greenshot/Helpers/WindowWrapper.cs +++ b/Greenshot/Helpers/WindowWrapper.cs @@ -31,6 +31,6 @@ namespace Greenshot.Helpers { get { return _hwnd; } } - private IntPtr _hwnd; + private readonly IntPtr _hwnd; } } diff --git a/Greenshot/Memento/AddElementMemento.cs b/Greenshot/Memento/AddElementMemento.cs index 91f3fcd3b..98a70214e 100644 --- a/Greenshot/Memento/AddElementMemento.cs +++ b/Greenshot/Memento/AddElementMemento.cs @@ -28,12 +28,12 @@ namespace Greenshot.Memento { /// The AddElementMemento makes it possible to undo adding an element /// public class AddElementMemento : IMemento { - private IDrawableContainer drawableContainer; - private Surface surface; + private IDrawableContainer _drawableContainer; + private Surface _surface; public AddElementMemento(Surface surface, IDrawableContainer drawableContainer) { - this.surface = surface; - this.drawableContainer = drawableContainer; + _surface = surface; + _drawableContainer = drawableContainer; } public void Dispose() { @@ -43,8 +43,8 @@ namespace Greenshot.Memento { protected virtual void Dispose(bool disposing) { //if (disposing) { } - drawableContainer = null; - surface = null; + _drawableContainer = null; + _surface = null; } public LangKey ActionLanguageKey { @@ -59,16 +59,15 @@ namespace Greenshot.Memento { public IMemento Restore() { // Before - drawableContainer.Invalidate(); + _drawableContainer.Invalidate(); // Store the selected state, as it's overwritten by the RemoveElement - bool selected = drawableContainer.Selected; - DeleteElementMemento oldState = new DeleteElementMemento(surface, drawableContainer); - surface.RemoveElement(drawableContainer, false); - drawableContainer.Selected = true; + DeleteElementMemento oldState = new DeleteElementMemento(_surface, _drawableContainer); + _surface.RemoveElement(_drawableContainer, false); + _drawableContainer.Selected = true; // After - drawableContainer.Invalidate(); + _drawableContainer.Invalidate(); return oldState; } } diff --git a/Greenshot/Memento/ChangeFieldHolderMemento.cs b/Greenshot/Memento/ChangeFieldHolderMemento.cs index 0c4911ae1..03a04ab5d 100644 --- a/Greenshot/Memento/ChangeFieldHolderMemento.cs +++ b/Greenshot/Memento/ChangeFieldHolderMemento.cs @@ -29,8 +29,8 @@ namespace Greenshot.Memento { /// public class ChangeFieldHolderMemento : IMemento { private IDrawableContainer drawableContainer; - private Field fieldToBeChanged; - private object oldValue; + private readonly Field fieldToBeChanged; + private readonly object oldValue; public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, Field fieldToBeChanged) { this.drawableContainer = drawableContainer; diff --git a/Greenshot/Memento/DeleteElementMemento.cs b/Greenshot/Memento/DeleteElementMemento.cs index ba532b11c..b715e26a8 100644 --- a/Greenshot/Memento/DeleteElementMemento.cs +++ b/Greenshot/Memento/DeleteElementMemento.cs @@ -29,7 +29,7 @@ namespace Greenshot.Memento { /// public class DeleteElementMemento : IMemento { private IDrawableContainer drawableContainer; - private Surface surface; + private readonly Surface surface; public DeleteElementMemento(Surface surface, IDrawableContainer drawableContainer) { this.surface = surface; diff --git a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs index e4aded8c6..940fbd4ee 100644 --- a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs +++ b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs @@ -31,8 +31,8 @@ namespace Greenshot.Memento { /// The DrawableContainerBoundsChangeMemento makes it possible to undo-redo an IDrawableContainer resize & move /// public class DrawableContainerBoundsChangeMemento : IMemento { - List points = new List(); - List sizes = new List(); + readonly List points = new List(); + readonly List sizes = new List(); List listOfdrawableContainer; private void StoreBounds() { diff --git a/Greenshot/Memento/TextChangeMemento.cs b/Greenshot/Memento/TextChangeMemento.cs index 541b4c06e..716b9e171 100644 --- a/Greenshot/Memento/TextChangeMemento.cs +++ b/Greenshot/Memento/TextChangeMemento.cs @@ -28,7 +28,7 @@ namespace Greenshot.Memento { /// public class TextChangeMemento : IMemento { private TextContainer textContainer; - private string oldText; + private readonly string oldText; public TextChangeMemento(TextContainer textContainer) { this.textContainer = textContainer; diff --git a/Greenshot/Processors/TitleFixProcessor.cs b/Greenshot/Processors/TitleFixProcessor.cs index d20798db2..a7b278d59 100644 --- a/Greenshot/Processors/TitleFixProcessor.cs +++ b/Greenshot/Processors/TitleFixProcessor.cs @@ -32,8 +32,8 @@ namespace Greenshot.Processors { /// Description of TitleFixProcessor. /// public class TitleFixProcessor : AbstractProcessor { - private static ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor)); - private static CoreConfiguration config = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor)); + private static readonly CoreConfiguration config = IniConfig.GetIniSection(); public TitleFixProcessor() { List corruptKeys = new List(); diff --git a/GreenshotBoxPlugin/BoxCredentials.cs b/GreenshotBoxPlugin/BoxCredentials.cs index 5d70729ed..b725ff72d 100644 --- a/GreenshotBoxPlugin/BoxCredentials.cs +++ b/GreenshotBoxPlugin/BoxCredentials.cs @@ -18,7 +18,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; namespace GreenshotBoxPlugin { /// diff --git a/GreenshotBoxPlugin/BoxDestination.cs b/GreenshotBoxPlugin/BoxDestination.cs index 6e2606fbd..6f5a3976e 100644 --- a/GreenshotBoxPlugin/BoxDestination.cs +++ b/GreenshotBoxPlugin/BoxDestination.cs @@ -22,12 +22,9 @@ using System.ComponentModel; using System.Drawing; using Greenshot.Plugin; using GreenshotPlugin.Core; -using log4net; namespace GreenshotBoxPlugin { public class BoxDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(BoxDestination)); - private readonly BoxPlugin _plugin; public BoxDestination(BoxPlugin plugin) { _plugin = plugin; diff --git a/GreenshotBoxPlugin/Forms/SettingsForm.cs b/GreenshotBoxPlugin/Forms/SettingsForm.cs index 07b32373d..0c643692c 100644 --- a/GreenshotBoxPlugin/Forms/SettingsForm.cs +++ b/GreenshotBoxPlugin/Forms/SettingsForm.cs @@ -18,20 +18,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using System.Drawing; -using System.Windows.Forms; using GreenshotBoxPlugin.Forms; -using GreenshotPlugin.Core; namespace GreenshotBoxPlugin { /// /// Description of PasswordRequestForm. /// public partial class SettingsForm : BoxForm { - string boxTicket = string.Empty; - public SettingsForm(BoxConfiguration config) { // // The InitializeComponent() call is required for Windows Forms designer support. diff --git a/GreenshotPlugin/Controls/AnimatingForm.cs b/GreenshotPlugin/Controls/AnimatingForm.cs index 17f8baa38..3a64af991 100644 --- a/GreenshotPlugin/Controls/AnimatingForm.cs +++ b/GreenshotPlugin/Controls/AnimatingForm.cs @@ -21,9 +21,7 @@ using System; using System.Windows.Forms; -using GreenshotPlugin.Core; using GreenshotPlugin.UnmanagedHelpers; -using Greenshot.IniFile; using log4net; namespace GreenshotPlugin.Controls { @@ -33,8 +31,8 @@ namespace GreenshotPlugin.Controls { public class AnimatingForm : GreenshotForm { private static readonly ILog LOG = LogManager.GetLogger(typeof(AnimatingForm)); private const int DEFAULT_VREFRESH = 60; - private int vRefresh = 0; - private Timer timer = null; + private int _vRefresh; + private Timer _timer; /// /// This flag specifies if any animation is used @@ -49,27 +47,27 @@ namespace GreenshotPlugin.Controls { /// protected int VRefresh { get { - if (vRefresh == 0) { + if (_vRefresh == 0) { // get te hDC of the desktop to get the VREFRESH - using (SafeWindowDCHandle desktopHandle = SafeWindowDCHandle.fromDesktop()) { - vRefresh = GDI32.GetDeviceCaps(desktopHandle, DeviceCaps.VREFRESH); + using (SafeWindowDCHandle desktopHandle = SafeWindowDCHandle.FromDesktop()) { + _vRefresh = GDI32.GetDeviceCaps(desktopHandle, DeviceCaps.VREFRESH); } } // A vertical refresh rate value of 0 or 1 represents the display hardware's default refresh rate. // As there is currently no know way to get the default, we guess it. - if (vRefresh <= 1) { - vRefresh = DEFAULT_VREFRESH; + if (_vRefresh <= 1) { + _vRefresh = DEFAULT_VREFRESH; } - return vRefresh; + return _vRefresh; } } /// /// Check if we are in a Terminal Server session OR need to optimize for RDP / remote desktop connections /// - protected bool isTerminalServerSession { + protected bool IsTerminalServerSession { get { - return coreConfiguration.OptimizeForRDP || SystemInformation.TerminalServerSession; + return !coreConfiguration.DisableRDPOptimizing && (coreConfiguration.OptimizeForRDP || SystemInformation.TerminalServerSession); } } @@ -80,7 +78,7 @@ namespace GreenshotPlugin.Controls { /// Number of frames, 1 if in Terminal Server Session protected int FramesForMillis(int milliseconds) { // If we are in a Terminal Server Session we return 1 - if (isTerminalServerSession) { + if (IsTerminalServerSession) { return 1; } return milliseconds / VRefresh; @@ -92,17 +90,17 @@ namespace GreenshotPlugin.Controls { protected AnimatingForm() { Load += delegate { if (EnableAnimation) { - timer = new Timer(); - timer.Interval = 1000 / VRefresh; - timer.Tick += new EventHandler(timer_Tick); - timer.Start(); + _timer = new Timer(); + _timer.Interval = 1000 / VRefresh; + _timer.Tick += timer_Tick; + _timer.Start(); } }; // Unregister at close FormClosing += delegate { - if (timer != null) { - timer.Stop(); + if (_timer != null) { + _timer.Stop(); } }; } diff --git a/GreenshotPlugin/Controls/BackgroundForm.cs b/GreenshotPlugin/Controls/BackgroundForm.cs index e3d73ac4d..888a7a275 100644 --- a/GreenshotPlugin/Controls/BackgroundForm.cs +++ b/GreenshotPlugin/Controls/BackgroundForm.cs @@ -29,7 +29,7 @@ namespace GreenshotPlugin.Controls { /// Description of PleaseWaitForm. /// public partial class BackgroundForm : Form { - private volatile bool shouldClose = false; + private volatile bool _shouldClose; private void BackgroundShowDialog() { ShowDialog(); @@ -38,7 +38,7 @@ namespace GreenshotPlugin.Controls { public static BackgroundForm ShowAndWait(string title, string text) { BackgroundForm backgroundForm = new BackgroundForm(title, text); // Show form in background thread - Thread backgroundTask = new Thread (new ThreadStart(backgroundForm.BackgroundShowDialog)); + Thread backgroundTask = new Thread (backgroundForm.BackgroundShowDialog); backgroundForm.Name = "Background form"; backgroundTask.IsBackground = true; backgroundTask.SetApartmentState(ApartmentState.STA); @@ -52,7 +52,7 @@ namespace GreenshotPlugin.Controls { // InitializeComponent(); Icon = GreenshotResources.getGreenshotIcon(); - shouldClose = false; + _shouldClose = false; Text = title; label_pleasewait.Text = text; FormClosing += PreventFormClose; @@ -76,20 +76,20 @@ namespace GreenshotPlugin.Controls { } private void PreventFormClose(object sender, FormClosingEventArgs e) { - if(!shouldClose) { + if(!_shouldClose) { e.Cancel = true; } } private void Timer_checkforcloseTick(object sender, EventArgs e) { - if (shouldClose) { + if (_shouldClose) { timer_checkforclose.Stop(); BeginInvoke(new EventHandler( delegate {Close();})); } } public void CloseDialog() { - shouldClose = true; + _shouldClose = true; Application.DoEvents(); } diff --git a/GreenshotPlugin/Controls/ExtendedWebBrowser.cs b/GreenshotPlugin/Controls/ExtendedWebBrowser.cs index 785fb37ee..98d93ba87 100644 --- a/GreenshotPlugin/Controls/ExtendedWebBrowser.cs +++ b/GreenshotPlugin/Controls/ExtendedWebBrowser.cs @@ -19,8 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Collections.Generic; -using System.Text; using System.Windows.Forms; using GreenshotInterop.Interop; @@ -30,7 +28,7 @@ namespace GreenshotPlugin.Controls { const int OLECMDID_SHOWSCRIPTERROR = 40; const int OLECMDID_SHOWMESSAGE = 41; - static Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836"); + static readonly Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836"); const int S_OK = 0; const int OLECMDERR_E_NOTSUPPORTED = (-2147221248); diff --git a/GreenshotPlugin/Controls/FormWithoutActivation.cs b/GreenshotPlugin/Controls/FormWithoutActivation.cs index 2b92989a5..8ab4ada3d 100644 --- a/GreenshotPlugin/Controls/FormWithoutActivation.cs +++ b/GreenshotPlugin/Controls/FormWithoutActivation.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; namespace GreenshotPlugin.Controls { diff --git a/GreenshotPlugin/Controls/GreenshotButton.cs b/GreenshotPlugin/Controls/GreenshotButton.cs index 530c34a89..e4e6d72b7 100644 --- a/GreenshotPlugin/Controls/GreenshotButton.cs +++ b/GreenshotPlugin/Controls/GreenshotButton.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/GreenshotCheckBox.cs b/GreenshotPlugin/Controls/GreenshotCheckBox.cs index 30aa74712..4872ba28d 100644 --- a/GreenshotPlugin/Controls/GreenshotCheckBox.cs +++ b/GreenshotPlugin/Controls/GreenshotCheckBox.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; @@ -33,16 +33,8 @@ namespace GreenshotPlugin.Controls { set; } - private string sectionName = "Core"; [Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")] - public string SectionName { - get { - return sectionName; - } - set { - sectionName = value; - } - } + public string SectionName { get; set; } = "Core"; [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName { diff --git a/GreenshotPlugin/Controls/GreenshotColumnSorter.cs b/GreenshotPlugin/Controls/GreenshotColumnSorter.cs index a64a4aabb..24c5f561d 100644 --- a/GreenshotPlugin/Controls/GreenshotColumnSorter.cs +++ b/GreenshotPlugin/Controls/GreenshotColumnSorter.cs @@ -29,28 +29,28 @@ namespace GreenshotPlugin.Controls { /// /// Specifies the column to be sorted /// - private int ColumnToSort; + private int _columnToSort; /// /// Specifies the order in which to sort (i.e. 'Ascending'). /// - private SortOrder OrderOfSort; + private SortOrder _orderOfSort; /// /// Case insensitive comparer object /// - private CaseInsensitiveComparer ObjectCompare; + private readonly CaseInsensitiveComparer _objectCompare; /// /// Class constructor. Initializes various elements /// public GreenshotColumnSorter() { // Initialize the column to '0' - ColumnToSort = 0; + _columnToSort = 0; // Initialize the sort order to 'none' - OrderOfSort = SortOrder.None; + _orderOfSort = SortOrder.None; // Initialize the CaseInsensitiveComparer object - ObjectCompare = new CaseInsensitiveComparer(); + _objectCompare = new CaseInsensitiveComparer(); } /// @@ -60,34 +60,33 @@ namespace GreenshotPlugin.Controls { /// Second object to be compared /// The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y' public int Compare(object x, object y) { - int compareResult; - ListViewItem listviewX, listviewY; - if (x == null && y == null) { return 0; - } else if (x == null && y != null) { - return -1; - } else if (x != null && y == null) { - return 1; + } + if (x == null) { + return -1; + } + if (y == null) { + return 1; } // Cast the objects to be compared to ListViewItem objects - listviewX = (ListViewItem)x; - listviewY = (ListViewItem)y; + var listviewX = (ListViewItem)x; + var listviewY = (ListViewItem)y; // Compare the two items - compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text); + var compareResult = _objectCompare.Compare(listviewX.SubItems[_columnToSort].Text, listviewY.SubItems[_columnToSort].Text); // Calculate correct return value based on object comparison - if (OrderOfSort == SortOrder.Ascending) { + if (_orderOfSort == SortOrder.Ascending) { // Ascending sort is selected, return normal result of compare operation return compareResult; - } else if (OrderOfSort == SortOrder.Descending) { - // Descending sort is selected, return negative result of compare operation - return (-compareResult); - } else { - // Return '0' to indicate they are equal - return 0; } + if (_orderOfSort == SortOrder.Descending) { + // Descending sort is selected, return negative result of compare operation + return -compareResult; + } + // Return '0' to indicate they are equal + return 0; } /// @@ -95,10 +94,10 @@ namespace GreenshotPlugin.Controls { /// public int SortColumn { set { - ColumnToSort = value; + _columnToSort = value; } get { - return ColumnToSort; + return _columnToSort; } } @@ -107,10 +106,10 @@ namespace GreenshotPlugin.Controls { /// public SortOrder Order { set { - OrderOfSort = value; + _orderOfSort = value; } get { - return OrderOfSort; + return _orderOfSort; } } } diff --git a/GreenshotPlugin/Controls/GreenshotComboBox.cs b/GreenshotPlugin/Controls/GreenshotComboBox.cs index 0fe165061..8adf83fc6 100644 --- a/GreenshotPlugin/Controls/GreenshotComboBox.cs +++ b/GreenshotPlugin/Controls/GreenshotComboBox.cs @@ -25,18 +25,11 @@ using GreenshotPlugin.Core; namespace GreenshotPlugin.Controls { public class GreenshotComboBox : ComboBox, IGreenshotConfigBindable { - private Type enumType = null; - private Enum selectedEnum = null; - private string sectionName = "Core"; + private Type _enumType; + private Enum _selectedEnum; + [Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")] - public string SectionName { - get { - return sectionName; - } - set { - sectionName = value; - } - } + public string SectionName { get; set; } = "Core"; [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName { @@ -52,7 +45,7 @@ namespace GreenshotPlugin.Controls { public void SetValue(Enum currentValue) { if (currentValue != null) { - selectedEnum = currentValue; + _selectedEnum = currentValue; SelectedItem = Language.Translate(currentValue); } } @@ -64,11 +57,10 @@ namespace GreenshotPlugin.Controls { /// TEnum to populate with public void Populate(Type enumType) { // Store the enum-type, so we can work with it - this.enumType = enumType; + _enumType = enumType; var availableValues = Enum.GetValues(enumType); Items.Clear(); - string enumTypeName = enumType.Name; foreach (var enumValue in availableValues) { Items.Add(Language.Translate((Enum)enumValue)); } @@ -78,26 +70,27 @@ namespace GreenshotPlugin.Controls { /// Store the selected value internally /// private void StoreSelectedEnum() { - string enumTypeName = enumType.Name; + string enumTypeName = _enumType.Name; string selectedValue = SelectedItem as string; - var availableValues = Enum.GetValues(enumType); + var availableValues = Enum.GetValues(_enumType); object returnValue = null; try { - returnValue = Enum.Parse(enumType, selectedValue); + returnValue = Enum.Parse(_enumType, selectedValue); } catch (Exception) { + // Ignore } foreach (Enum enumValue in availableValues) { - string enumKey = enumTypeName + "." + enumValue.ToString(); + string enumKey = enumTypeName + "." + enumValue; if (Language.hasKey(enumKey)) { - string translation = Language.GetString(enumTypeName + "." + enumValue.ToString()); + string translation = Language.GetString(enumTypeName + "." + enumValue); if (translation.Equals(selectedValue)) { returnValue = enumValue; } } } - selectedEnum = (Enum)returnValue; + _selectedEnum = (Enum)returnValue; } /// @@ -105,7 +98,7 @@ namespace GreenshotPlugin.Controls { /// /// The enum value of the combobox public Enum GetSelectedEnum() { - return selectedEnum; + return _selectedEnum; } } } diff --git a/GreenshotPlugin/Controls/GreenshotForm.cs b/GreenshotPlugin/Controls/GreenshotForm.cs index ab151675a..b44003b58 100644 --- a/GreenshotPlugin/Controls/GreenshotForm.cs +++ b/GreenshotPlugin/Controls/GreenshotForm.cs @@ -34,13 +34,13 @@ namespace GreenshotPlugin.Controls { /// This form is used for automatically binding the elements of the form to the language /// public class GreenshotForm : Form, IGreenshotLanguageBindable { - private static ILog LOG = LogManager.GetLogger(typeof(GreenshotForm)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(GreenshotForm)); protected static CoreConfiguration coreConfiguration; - private static IDictionary reflectionCache = new Dictionary(); + private static readonly IDictionary reflectionCache = new Dictionary(); private IComponentChangeService m_changeService; - private bool _isDesignModeLanguageSet = false; - private bool _applyLanguageManually = false; - private bool _storeFieldsManually = false; + private bool _isDesignModeLanguageSet; + private bool _applyLanguageManually; + private bool _storeFieldsManually; private IDictionary _designTimeControls; private IDictionary _designTimeToolStripItems; @@ -210,16 +210,16 @@ namespace GreenshotPlugin.Controls { // Clear our the component change events to prepare for re-siting. if (m_changeService != null) { - m_changeService.ComponentChanged -= new ComponentChangedEventHandler(OnComponentChanged); - m_changeService.ComponentAdded -= new ComponentEventHandler(OnComponentAdded); + m_changeService.ComponentChanged -= OnComponentChanged; + m_changeService.ComponentAdded -= OnComponentAdded; } } private void RegisterChangeNotifications() { // Register the event handlers for the IComponentChangeService events if (m_changeService != null) { - m_changeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); - m_changeService.ComponentAdded += new ComponentEventHandler(OnComponentAdded); + m_changeService.ComponentChanged += OnComponentChanged; + m_changeService.ComponentAdded += OnComponentAdded; } } @@ -277,7 +277,7 @@ namespace GreenshotPlugin.Controls { } protected void ApplyLanguage(ToolStripItem applyTo, string languageKey) { - string langString = null; + string langString; if (!string.IsNullOrEmpty(languageKey)) { if (!Language.TryGetString(languageKey, out langString)) { LOG.WarnFormat("Unknown language key '{0}' configured for control '{1}', this might be okay.", languageKey, applyTo.Name); @@ -473,7 +473,6 @@ namespace GreenshotPlugin.Controls { comboxBox.Populate(iniValue.ValueType); comboxBox.SetValue((Enum)iniValue.Value); comboxBox.Enabled = !iniValue.IsFixed; - continue; } } } diff --git a/GreenshotPlugin/Controls/GreenshotGroupBox.cs b/GreenshotPlugin/Controls/GreenshotGroupBox.cs index b83ce53c9..5dfcae4a5 100644 --- a/GreenshotPlugin/Controls/GreenshotGroupBox.cs +++ b/GreenshotPlugin/Controls/GreenshotGroupBox.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; using System.ComponentModel; diff --git a/GreenshotPlugin/Controls/GreenshotLabel.cs b/GreenshotPlugin/Controls/GreenshotLabel.cs index 813eb7aa5..13afbb633 100644 --- a/GreenshotPlugin/Controls/GreenshotLabel.cs +++ b/GreenshotPlugin/Controls/GreenshotLabel.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; using System.ComponentModel; diff --git a/GreenshotPlugin/Controls/GreenshotRadioButton.cs b/GreenshotPlugin/Controls/GreenshotRadioButton.cs index 9de1d2147..e87e95818 100644 --- a/GreenshotPlugin/Controls/GreenshotRadioButton.cs +++ b/GreenshotPlugin/Controls/GreenshotRadioButton.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/GreenshotTabPage.cs b/GreenshotPlugin/Controls/GreenshotTabPage.cs index 9e95517b1..c3f1e42cf 100644 --- a/GreenshotPlugin/Controls/GreenshotTabPage.cs +++ b/GreenshotPlugin/Controls/GreenshotTabPage.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; using System.ComponentModel; diff --git a/GreenshotPlugin/Controls/GreenshotTextBox.cs b/GreenshotPlugin/Controls/GreenshotTextBox.cs index 772520bcd..ecaaa117f 100644 --- a/GreenshotPlugin/Controls/GreenshotTextBox.cs +++ b/GreenshotPlugin/Controls/GreenshotTextBox.cs @@ -18,22 +18,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; namespace GreenshotPlugin.Controls { public class GreenshotTextBox : TextBox, IGreenshotConfigBindable { - private string sectionName = "Core"; [Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")] - public string SectionName { - get { - return sectionName; - } - set { - sectionName = value; - } - } + public string SectionName { get; set; } = "Core"; [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName { diff --git a/GreenshotPlugin/Controls/GreenshotToolDropDownButton.cs b/GreenshotPlugin/Controls/GreenshotToolDropDownButton.cs index 48301b72d..d4ffdff47 100644 --- a/GreenshotPlugin/Controls/GreenshotToolDropDownButton.cs +++ b/GreenshotPlugin/Controls/GreenshotToolDropDownButton.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/GreenshotToolStripButton.cs b/GreenshotPlugin/Controls/GreenshotToolStripButton.cs index 3678081f0..5205f5434 100644 --- a/GreenshotPlugin/Controls/GreenshotToolStripButton.cs +++ b/GreenshotPlugin/Controls/GreenshotToolStripButton.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/GreenshotToolStripLabel.cs b/GreenshotPlugin/Controls/GreenshotToolStripLabel.cs index 615b9206e..19378027b 100644 --- a/GreenshotPlugin/Controls/GreenshotToolStripLabel.cs +++ b/GreenshotPlugin/Controls/GreenshotToolStripLabel.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; using System.ComponentModel; diff --git a/GreenshotPlugin/Controls/GreenshotToolStripMenuItem.cs b/GreenshotPlugin/Controls/GreenshotToolStripMenuItem.cs index 2ef417fd9..6c3e1572c 100644 --- a/GreenshotPlugin/Controls/GreenshotToolStripMenuItem.cs +++ b/GreenshotPlugin/Controls/GreenshotToolStripMenuItem.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/HotkeyControl.cs b/GreenshotPlugin/Controls/HotkeyControl.cs index 706e5316f..372e67633 100644 --- a/GreenshotPlugin/Controls/HotkeyControl.cs +++ b/GreenshotPlugin/Controls/HotkeyControl.cs @@ -22,6 +22,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; @@ -37,13 +38,13 @@ namespace GreenshotPlugin.Controls { /// But is modified to fit in Greenshot, and have localized support /// public class HotkeyControl : GreenshotTextBox { - private static ILog LOG = LogManager.GetLogger(typeof(HotkeyControl)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(HotkeyControl)); - private static EventDelay eventDelay = new EventDelay(TimeSpan.FromMilliseconds(600).Ticks); - private static bool isWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1; + private static readonly EventDelay eventDelay = new EventDelay(TimeSpan.FromMilliseconds(600).Ticks); + private static readonly bool isWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1; // Holds the list of hotkeys - private static Dictionary keyHandlers = new Dictionary(); + private static readonly IDictionary keyHandlers = new Dictionary(); private static int hotKeyCounter = 1; private const uint WM_HOTKEY = 0x312; private static IntPtr hotkeyHWND; @@ -57,6 +58,7 @@ namespace GreenshotPlugin.Controls { // } // } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum Modifiers : uint { NONE = 0, ALT = 1, @@ -66,6 +68,7 @@ namespace GreenshotPlugin.Controls { NO_REPEAT = 0x4000 } + [SuppressMessage("ReSharper", "InconsistentNaming")] private enum MapType : uint { MAPVK_VK_TO_VSC = 0, //The uCode parameter is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the function returns 0. MAPVK_VSC_TO_VK = 1, //The uCode parameter is a scan code and is translated into a virtual-key code that does not distinguish between left- and right-hand keys. If there is no translation, the function returns 0. @@ -93,10 +96,10 @@ namespace GreenshotPlugin.Controls { // ArrayLists used to enforce the use of proper modifiers. // Shift+A isn't a valid hotkey, for instance, as it would screw up when the user is typing. - private ArrayList needNonShiftModifier = null; - private ArrayList needNonAltGrModifier = null; + private readonly ArrayList needNonShiftModifier; + private readonly ArrayList needNonAltGrModifier; - private ContextMenu dummy = new ContextMenu(); + private readonly ContextMenu dummy = new ContextMenu(); /// /// Used to make sure that there is no right-click menu available @@ -131,9 +134,9 @@ namespace GreenshotPlugin.Controls { Text = "None"; // Handle events that occurs when keys are pressed - KeyPress += new KeyPressEventHandler(HotkeyControl_KeyPress); - KeyUp += new KeyEventHandler(HotkeyControl_KeyUp); - KeyDown += new KeyEventHandler(HotkeyControl_KeyDown); + KeyPress += HotkeyControl_KeyPress; + KeyUp += HotkeyControl_KeyUp; + KeyDown += HotkeyControl_KeyDown; // Fill the ArrayLists that contain all invalid hotkey combinations needNonShiftModifier = new ArrayList(); diff --git a/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs b/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs index e17e9f112..67ab07c40 100644 --- a/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs +++ b/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs @@ -18,7 +18,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; namespace GreenshotPlugin.Controls { public interface IGreenshotConfigBindable { diff --git a/GreenshotPlugin/Controls/IGreenshotLanguageBindable.cs b/GreenshotPlugin/Controls/IGreenshotLanguageBindable.cs index 899f78134..8a84786b1 100644 --- a/GreenshotPlugin/Controls/IGreenshotLanguageBindable.cs +++ b/GreenshotPlugin/Controls/IGreenshotLanguageBindable.cs @@ -18,7 +18,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; namespace GreenshotPlugin.Controls { /// diff --git a/GreenshotPlugin/Controls/OAuthLoginForm.cs b/GreenshotPlugin/Controls/OAuthLoginForm.cs index e562b1185..d0a9e017d 100644 --- a/GreenshotPlugin/Controls/OAuthLoginForm.cs +++ b/GreenshotPlugin/Controls/OAuthLoginForm.cs @@ -20,12 +20,8 @@ */ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Text; using System.Windows.Forms; -using System.Web; -using System.Collections.Specialized; using GreenshotPlugin.Core; using log4net; @@ -35,8 +31,8 @@ namespace GreenshotPlugin.Controls { /// public partial class OAuthLoginForm : Form { private static readonly ILog LOG = LogManager.GetLogger(typeof(OAuthLoginForm)); - private string _callbackUrl = null; - private IDictionary _callbackParameters = null; + private readonly string _callbackUrl; + private IDictionary _callbackParameters; public IDictionary CallbackParameters { get { diff --git a/GreenshotPlugin/Controls/PleaseWaitForm.cs b/GreenshotPlugin/Controls/PleaseWaitForm.cs index 63a0c783b..53cb527f9 100644 --- a/GreenshotPlugin/Controls/PleaseWaitForm.cs +++ b/GreenshotPlugin/Controls/PleaseWaitForm.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Drawing; using System.Windows.Forms; using System.Threading; using GreenshotPlugin.Core; @@ -30,8 +29,8 @@ namespace GreenshotPlugin.Controls { /// Description of PleaseWaitForm. /// public partial class PleaseWaitForm : Form { - private static ILog LOG = LogManager.GetLogger(typeof(PleaseWaitForm)); - private Thread waitFor = null; + private static readonly ILog LOG = LogManager.GetLogger(typeof(PleaseWaitForm)); + private Thread waitFor; private string title; public PleaseWaitForm() { // diff --git a/GreenshotPlugin/Controls/QualityDialog.cs b/GreenshotPlugin/Controls/QualityDialog.cs index c601c8e88..000564bf1 100644 --- a/GreenshotPlugin/Controls/QualityDialog.cs +++ b/GreenshotPlugin/Controls/QualityDialog.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Windows.Forms; using GreenshotPlugin.Core; using Greenshot.IniFile; using Greenshot.Plugin; @@ -29,7 +28,7 @@ namespace GreenshotPlugin.Controls { /// Description of JpegQualityDialog. /// public partial class QualityDialog : GreenshotForm { - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); public SurfaceOutputSettings Settings { get; set; diff --git a/GreenshotPlugin/Controls/SaveImageFileDialog.cs b/GreenshotPlugin/Controls/SaveImageFileDialog.cs index bf14f2be0..9e94d595f 100644 --- a/GreenshotPlugin/Controls/SaveImageFileDialog.cs +++ b/GreenshotPlugin/Controls/SaveImageFileDialog.cs @@ -33,12 +33,12 @@ namespace GreenshotPlugin.Controls { /// For some reason SFD is sealed :( /// public class SaveImageFileDialog : IDisposable { - private static ILog LOG = LogManager.GetLogger(typeof(SaveImageFileDialog)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); - protected SaveFileDialog saveFileDialog; - private FilterOption[] filterOptions; - private DirectoryInfo eagerlyCreatedDirectory; - private ICaptureDetails captureDetails = null; + private static readonly ILog LOG = LogManager.GetLogger(typeof(SaveImageFileDialog)); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + protected SaveFileDialog SaveFileDialog; + private FilterOption[] _filterOptions; + private DirectoryInfo _eagerlyCreatedDirectory; + private readonly ICaptureDetails _captureDetails; public void Dispose() { Dispose(true); @@ -47,25 +47,25 @@ namespace GreenshotPlugin.Controls { protected virtual void Dispose(bool disposing) { if (disposing) { - if (saveFileDialog != null) { - saveFileDialog.Dispose(); - saveFileDialog = null; + if (SaveFileDialog != null) { + SaveFileDialog.Dispose(); + SaveFileDialog = null; } } } public SaveImageFileDialog() { - init(); + Init(); } public SaveImageFileDialog(ICaptureDetails captureDetails) { - this.captureDetails = captureDetails; - init(); + _captureDetails = captureDetails; + Init(); } - private void init() { - saveFileDialog = new SaveFileDialog(); - applyFilterOptions(); + private void Init() { + SaveFileDialog = new SaveFileDialog(); + ApplyFilterOptions(); string initialDirectory = null; try { initialDirectory = Path.GetDirectoryName(conf.OutputFileAsFullpath); @@ -74,44 +74,46 @@ namespace GreenshotPlugin.Controls { } if (!string.IsNullOrEmpty(initialDirectory) && Directory.Exists(initialDirectory)) { - saveFileDialog.InitialDirectory = initialDirectory; + SaveFileDialog.InitialDirectory = initialDirectory; } else if (Directory.Exists(conf.OutputFilePath)) { - saveFileDialog.InitialDirectory = conf.OutputFilePath; + SaveFileDialog.InitialDirectory = conf.OutputFilePath; } // The following property fixes a problem that the directory where we save is locked (bug #2899790) - saveFileDialog.RestoreDirectory = true; - saveFileDialog.OverwritePrompt = true; - saveFileDialog.CheckPathExists = false; - saveFileDialog.AddExtension = true; + SaveFileDialog.RestoreDirectory = true; + SaveFileDialog.OverwritePrompt = true; + SaveFileDialog.CheckPathExists = false; + SaveFileDialog.AddExtension = true; ApplySuggestedValues(); } - private void applyFilterOptions() { - prepareFilterOptions(); + private void ApplyFilterOptions() { + PrepareFilterOptions(); string fdf = ""; int preselect = 0; var outputFileFormatAsString = Enum.GetName(typeof(OutputFormat), conf.OutputFileFormat); - for(int i=0; i public string FileName { - get {return saveFileDialog.FileName;} - set {saveFileDialog.FileName = value;} + get {return SaveFileDialog.FileName;} + set {SaveFileDialog.FileName = value;} } /// /// initial directory of the dialog /// public string InitialDirectory { - get {return saveFileDialog.InitialDirectory;} - set {saveFileDialog.InitialDirectory = value;} + get {return SaveFileDialog.InitialDirectory;} + set {SaveFileDialog.InitialDirectory = value;} } /// @@ -138,7 +140,7 @@ namespace GreenshotPlugin.Controls { /// public string FileNameWithExtension { get { - string fn = saveFileDialog.FileName; + string fn = SaveFileDialog.FileName; // if the filename contains a valid extension, which is the same like the selected filter item's extension, the filename is okay if(fn.EndsWith(Extension,StringComparison.CurrentCultureIgnoreCase)) return fn; // otherwise we just add the selected filter item's extension @@ -155,19 +157,19 @@ namespace GreenshotPlugin.Controls { /// public string Extension { get { - return filterOptions[saveFileDialog.FilterIndex-1].Extension; + return _filterOptions[SaveFileDialog.FilterIndex-1].Extension; } set { - for(int i=0; i /// sets InitialDirectory and FileName property of a SaveFileDialog smartly, considering default pattern and last used path /// - /// a SaveFileDialog instance private void ApplySuggestedValues() { // build the full path and set dialog properties - FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, captureDetails); + FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, _captureDetails); } - - private string GetRootDirFromConfig() { - string rootDir = conf.OutputFilePath; - rootDir = FilenameHelper.FillVariables(rootDir, false); - return rootDir; - } - + private class FilterOption { public string Label; public string Extension; @@ -195,29 +190,14 @@ namespace GreenshotPlugin.Controls { private void CleanUp() { // fix for bug #3379053 try { - if(eagerlyCreatedDirectory != null && eagerlyCreatedDirectory.GetFiles().Length == 0 && eagerlyCreatedDirectory.GetDirectories().Length == 0) { - eagerlyCreatedDirectory.Delete(); - eagerlyCreatedDirectory = null; + if(_eagerlyCreatedDirectory != null && _eagerlyCreatedDirectory.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0) { + _eagerlyCreatedDirectory.Delete(); + _eagerlyCreatedDirectory = null; } } catch (Exception e) { LOG.WarnFormat("Couldn't cleanup directory due to: {0}", e.Message); - eagerlyCreatedDirectory = null; + _eagerlyCreatedDirectory = null; } } - - private string CreateDirectoryIfNotExists(string fullPath) { - string dirName = null; - try { - dirName = Path.GetDirectoryName(fullPath); - DirectoryInfo di = new DirectoryInfo(dirName); - if(!di.Exists) { - di = Directory.CreateDirectory(dirName); - eagerlyCreatedDirectory = di; - } - } catch (Exception e) { - LOG.Error("Error in CreateDirectoryIfNotExists",e); - } - return dirName; - } } } diff --git a/GreenshotPlugin/Controls/ThumbnailForm.cs b/GreenshotPlugin/Controls/ThumbnailForm.cs index 7f5053399..121798e00 100644 --- a/GreenshotPlugin/Controls/ThumbnailForm.cs +++ b/GreenshotPlugin/Controls/ThumbnailForm.cs @@ -31,10 +31,9 @@ namespace GreenshotPlugin.Controls { /// Didn't make it completely "generic" yet, but at least most logic is in here so we don't have it in the mainform. /// public class ThumbnailForm : FormWithoutActivation { - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private IntPtr thumbnailHandle = IntPtr.Zero; - private Rectangle parentMenuBounds = Rectangle.Empty; + private IntPtr _thumbnailHandle = IntPtr.Zero; public ThumbnailForm() { ShowInTaskbar = false; @@ -59,9 +58,9 @@ namespace GreenshotPlugin.Controls { } private void UnregisterThumbnail() { - if (thumbnailHandle != IntPtr.Zero) { - DWM.DwmUnregisterThumbnail(thumbnailHandle); - thumbnailHandle = IntPtr.Zero; + if (_thumbnailHandle != IntPtr.Zero) { + DWM.DwmUnregisterThumbnail(_thumbnailHandle); + _thumbnailHandle = IntPtr.Zero; } } @@ -73,10 +72,10 @@ namespace GreenshotPlugin.Controls { public void ShowThumbnail(WindowDetails window, Control parentControl) { UnregisterThumbnail(); - DWM.DwmRegisterThumbnail(Handle, window.Handle, out thumbnailHandle); - if (thumbnailHandle != IntPtr.Zero) { + DWM.DwmRegisterThumbnail(Handle, window.Handle, out _thumbnailHandle); + if (_thumbnailHandle != IntPtr.Zero) { SIZE sourceSize; - DWM.DwmQueryThumbnailSourceSize(thumbnailHandle, out sourceSize); + DWM.DwmQueryThumbnailSourceSize(_thumbnailHandle, out sourceSize); int thumbnailHeight = 200; int thumbnailWidth = (int)(thumbnailHeight * ((float)sourceSize.width / (float)sourceSize.height)); if (parentControl != null && thumbnailWidth > parentControl.Width) { @@ -86,12 +85,14 @@ namespace GreenshotPlugin.Controls { Width = thumbnailWidth; Height = thumbnailHeight; // Prepare the displaying of the Thumbnail - DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES(); - props.Opacity = (byte)255; - props.Visible = true; - props.SourceClientAreaOnly = false; - props.Destination = new RECT(0, 0, thumbnailWidth, thumbnailHeight); - DWM.DwmUpdateThumbnailProperties(thumbnailHandle, ref props); + DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES + { + Opacity = 255, + Visible = true, + SourceClientAreaOnly = false, + Destination = new RECT(0, 0, thumbnailWidth, thumbnailHeight) + }; + DWM.DwmUpdateThumbnailProperties(_thumbnailHandle, ref props); if (parentControl != null) { AlignToControl(parentControl); } diff --git a/GreenshotPlugin/Core/AbstractDestination.cs b/GreenshotPlugin/Core/AbstractDestination.cs index af74efb41..8fa0938b0 100644 --- a/GreenshotPlugin/Core/AbstractDestination.cs +++ b/GreenshotPlugin/Core/AbstractDestination.cs @@ -34,7 +34,7 @@ namespace GreenshotPlugin.Core { /// public abstract class AbstractDestination : IDestination { private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractDestination)); - private static CoreConfiguration configuration = IniConfig.GetIniSection(); + private static readonly CoreConfiguration configuration = IniConfig.GetIniSection(); public virtual int CompareTo(object obj) { IDestination other = obj as IDestination; @@ -312,7 +312,8 @@ namespace GreenshotPlugin.Core { basisMenuItem.Click += destinationClickHandler; if (isDynamic && addDynamics) { - basisMenuItem.DropDownOpening += delegate(object source, EventArgs eventArgs) { + basisMenuItem.DropDownOpening += delegate + { if (basisMenuItem.DropDownItems.Count == 0) { List subDestinations = new List(); // Fixing Bug #3536968 by catching the COMException (every exception) and not displaying the "subDestinations" diff --git a/GreenshotPlugin/Core/AccessibleHelper.cs b/GreenshotPlugin/Core/AccessibleHelper.cs index 914b27733..c54a2a51b 100644 --- a/GreenshotPlugin/Core/AccessibleHelper.cs +++ b/GreenshotPlugin/Core/AccessibleHelper.cs @@ -59,7 +59,7 @@ namespace GreenshotPlugin.Core { private const int IE_ACTIVE_TAB = 2097154; private const int CHILDID_SELF = 0; - private IAccessible accessible; + private readonly IAccessible accessible; private Accessible[] Children { get { int num = 0; diff --git a/GreenshotPlugin/Core/AnimationHelpers.cs b/GreenshotPlugin/Core/AnimationHelpers.cs index fe70fff73..3da6a5115 100644 --- a/GreenshotPlugin/Core/AnimationHelpers.cs +++ b/GreenshotPlugin/Core/AnimationHelpers.cs @@ -20,9 +20,7 @@ */ using System; using System.Drawing; -using System.Drawing.Drawing2D; using System.Collections.Generic; -using log4net; namespace GreenshotPlugin.Core { @@ -33,7 +31,7 @@ namespace GreenshotPlugin.Core { /// /// Is there a next frame? /// - bool hasNext { + bool HasNext { get; } /// @@ -81,12 +79,7 @@ namespace GreenshotPlugin.Core { /// /// Type for the animation, like Point/Rectangle/Size public abstract class AnimatorBase : IAnimator { - protected T first; - protected T last; - protected T current; - private Queue> queue = new Queue>(); - protected int frames; - protected int currentFrameNr = 0; + private readonly Queue> _queue = new Queue>(); /// /// Constructor @@ -97,10 +90,10 @@ namespace GreenshotPlugin.Core { /// /// public AnimatorBase(T first, T last, int frames, EasingType easingType, EasingMode easingMode) { - this.first = first; - this.last = last; - this.frames = frames; - current = first; + First = first; + Last = last; + Frames = frames; + Current = first; EasingType = easingType; EasingMode = easingMode; } @@ -109,39 +102,34 @@ namespace GreenshotPlugin.Core { /// The amount of frames /// public int Frames { - get { return frames; } + get; + private set; } /// /// Current frame number /// - public int CurrentFrameNr { - get { return currentFrameNr; } - } + public int CurrentFrameNr { get; private set; } /// /// First animation value /// - public T First { - get { return first; } - } + public T First { get; private set; } /// /// Last animation value, of this "leg" /// - public T Last { - get { return last; } - } + public T Last { get; private set; } /// /// Final animation value, this is including the legs /// public T Final { get { - if (queue.Count == 0) { - return last; + if (_queue.Count == 0) { + return Last; } - return queue.ToArray()[queue.Count - 1].Destination; + return _queue.ToArray()[_queue.Count - 1].Destination; } } @@ -150,7 +138,7 @@ namespace GreenshotPlugin.Core { /// /// public void ChangeDestination(T newDestination) { - ChangeDestination(newDestination, frames); + ChangeDestination(newDestination, Frames); } /// @@ -159,11 +147,11 @@ namespace GreenshotPlugin.Core { /// /// public void ChangeDestination(T newDestination, int frames) { - queue.Clear(); - first = current; - currentFrameNr = 0; - this.frames = frames; - last = newDestination; + _queue.Clear(); + First = Current; + CurrentFrameNr = 0; + Frames = frames; + Last = newDestination; } /// @@ -202,12 +190,14 @@ namespace GreenshotPlugin.Core { /// /// public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType, EasingMode easingMode) { - AnimationLeg leg = new AnimationLeg(); - leg.Destination = queuedDestination; - leg.Frames = frames; - leg.EasingType = easingType; - leg.EasingMode = easingMode; - queue.Enqueue(leg); + AnimationLeg leg = new AnimationLeg + { + Destination = queuedDestination, + Frames = frames, + EasingType = easingType, + EasingMode = easingMode + }; + _queue.Enqueue(leg); } /// @@ -233,12 +223,12 @@ namespace GreenshotPlugin.Core { get { switch (EasingMode) { case EasingMode.EaseOut: - return Easing.EaseOut((double)currentFrameNr / (double)frames, EasingType); + return Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType); case EasingMode.EaseInOut: - return Easing.EaseInOut((double)currentFrameNr / (double)frames, EasingType); + return Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType); case EasingMode.EaseIn: default: - return Easing.EaseIn((double)currentFrameNr / (double)frames, EasingType); + return Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType); } } } @@ -246,27 +236,23 @@ namespace GreenshotPlugin.Core { /// /// Get the current (previous) frame object /// - public virtual T Current { - get { - return current; - } - } + public virtual T Current { get; set; } /// /// Returns if there are any frame left, and if this is the case than the frame is increased. /// public virtual bool NextFrame { get { - if (currentFrameNr < frames) { - currentFrameNr++; + if (CurrentFrameNr < Frames) { + CurrentFrameNr++; return true; } - if (queue.Count > 0) { - first = current; - currentFrameNr = 0; - AnimationLeg nextLeg = queue.Dequeue(); - last = nextLeg.Destination; - frames = nextLeg.Frames; + if (_queue.Count > 0) { + First = Current; + CurrentFrameNr = 0; + AnimationLeg nextLeg = _queue.Dequeue(); + Last = nextLeg.Destination; + Frames = nextLeg.Frames; EasingType = nextLeg.EasingType; EasingMode = nextLeg.EasingMode; return true; @@ -278,12 +264,12 @@ namespace GreenshotPlugin.Core { /// /// Are there more frames to animate? /// - public virtual bool hasNext { + public virtual bool HasNext { get { - if (currentFrameNr < frames) { + if (CurrentFrameNr < Frames) { return true; } - return queue.Count > 0; + return _queue.Count > 0; } } @@ -298,8 +284,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the RectangleAnimator /// public class RectangleAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(RectangleAnimator)); - public RectangleAnimator(Rectangle first, Rectangle last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -318,18 +302,18 @@ namespace GreenshotPlugin.Core { public override Rectangle Next() { if (NextFrame) { double easingValue = EasingValue; - double dx = last.X - first.X; - double dy = last.Y - first.Y; + double dx = Last.X - First.X; + double dy = Last.Y - First.Y; - int x = first.X + (int)(easingValue * dx); - int y = first.Y + (int)(easingValue * dy); - double dw = last.Width - first.Width; - double dh = last.Height - first.Height; - int width = first.Width + (int)(easingValue * dw); - int height = first.Height + (int)(easingValue * dh); - current = new Rectangle(x, y, width, height); + int x = First.X + (int)(easingValue * dx); + int y = First.Y + (int)(easingValue * dy); + double dw = Last.Width - First.Width; + double dh = Last.Height - First.Height; + int width = First.Width + (int)(easingValue * dw); + int height = First.Height + (int)(easingValue * dh); + Current = new Rectangle(x, y, width, height); } - return current; + return Current; } } @@ -337,7 +321,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the PointAnimator /// public class PointAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(PointAnimator)); public PointAnimator(Point first, Point last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -355,14 +338,14 @@ namespace GreenshotPlugin.Core { public override Point Next() { if (NextFrame) { double easingValue = EasingValue; - double dx = last.X - first.X; - double dy = last.Y - first.Y; + double dx = Last.X - First.X; + double dy = Last.Y - First.Y; - int x = first.X + (int)(easingValue * dx); - int y = first.Y + (int)(easingValue * dy); - current = new Point(x, y); + int x = First.X + (int)(easingValue * dx); + int y = First.Y + (int)(easingValue * dy); + Current = new Point(x, y); } - return current; + return Current; } } @@ -370,7 +353,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the SizeAnimator /// public class SizeAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(SizeAnimator)); public SizeAnimator(Size first, Size last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -388,13 +370,13 @@ namespace GreenshotPlugin.Core { public override Size Next() { if (NextFrame) { double easingValue = EasingValue; - double dw = last.Width - first.Width; - double dh = last.Height - first.Height; - int width = first.Width + (int)(easingValue * dw); - int height = first.Height + (int)(easingValue * dh); - current = new Size(width, height); + double dw = Last.Width - First.Width; + double dh = Last.Height - First.Height; + int width = First.Width + (int)(easingValue * dw); + int height = First.Height + (int)(easingValue * dh); + Current = new Size(width, height); } - return current; + return Current; } } @@ -402,7 +384,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the ColorAnimator /// public class ColorAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(ColorAnimator)); public ColorAnimator(Color first, Color last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -420,17 +401,17 @@ namespace GreenshotPlugin.Core { public override Color Next() { if (NextFrame) { double easingValue = EasingValue; - double da = last.A - first.A; - double dr = last.R - first.R; - double dg = last.G - first.G; - double db = last.B - first.B; - int a = first.A + (int)(easingValue * da); - int r = first.R + (int)(easingValue * dr); - int g = first.G + (int)(easingValue * dg); - int b = first.B + (int)(easingValue * db); - current = Color.FromArgb(a,r,g,b); + double da = Last.A - First.A; + double dr = Last.R - First.R; + double dg = Last.G - First.G; + double db = Last.B - First.B; + int a = First.A + (int)(easingValue * da); + int r = First.R + (int)(easingValue * dr); + int g = First.G + (int)(easingValue * dg); + int b = First.B + (int)(easingValue * db); + Current = Color.FromArgb(a,r,g,b); } - return current; + return Current; } } @@ -438,7 +419,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the IntAnimator /// public class IntAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(IntAnimator)); public IntAnimator(int first, int last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -456,10 +436,10 @@ namespace GreenshotPlugin.Core { public override int Next() { if (NextFrame) { double easingValue = EasingValue; - double delta = last - first; - current = first + (int)(easingValue * delta); + double delta = Last - First; + Current = First + (int)(easingValue * delta); } - return current; + return Current; } } @@ -470,7 +450,7 @@ namespace GreenshotPlugin.Core { // Adapted from http://www.robertpenner.com/easing/penner_chapter7_tweening.pdf public static double Ease(double linearStep, double acceleration, EasingType type) { - double easedStep = acceleration > 0 ? EaseIn(linearStep, type) : acceleration < 0 ? EaseOut(linearStep, type) : (double)linearStep; + double easedStep = acceleration > 0 ? EaseIn(linearStep, type) : acceleration < 0 ? EaseOut(linearStep, type) : linearStep; // Lerp: return ((easedStep - linearStep) * Math.Abs(acceleration) + linearStep); } diff --git a/GreenshotPlugin/Core/Cache.cs b/GreenshotPlugin/Core/Cache.cs index 894e389cc..06b98899f 100644 --- a/GreenshotPlugin/Core/Cache.cs +++ b/GreenshotPlugin/Core/Cache.cs @@ -31,10 +31,10 @@ namespace GreenshotPlugin.Core { /// Type of value public class Cache { private static readonly ILog LOG = LogManager.GetLogger(typeof(Cache)); - private IDictionary internalCache = new Dictionary(); - private object lockObject = new object(); - private int secondsToExpire = 10; - private CacheObjectExpired expiredCallback = null; + private readonly IDictionary internalCache = new Dictionary(); + private readonly object lockObject = new object(); + private readonly int secondsToExpire = 10; + private readonly CacheObjectExpired expiredCallback; public delegate void CacheObjectExpired(TK key, TV cacheValue); /// @@ -168,7 +168,7 @@ namespace GreenshotPlugin.Core { /// private class CachedItem { public event CacheObjectExpired Expired; - private int secondsToExpire; + private readonly int secondsToExpire; private readonly Timer _timerEvent; public CachedItem(TK key, TV item, int secondsToExpire) { diff --git a/GreenshotPlugin/Core/ClipboardHelper.cs b/GreenshotPlugin/Core/ClipboardHelper.cs index 7bb88cd61..9e7a545ea 100644 --- a/GreenshotPlugin/Core/ClipboardHelper.cs +++ b/GreenshotPlugin/Core/ClipboardHelper.cs @@ -327,9 +327,9 @@ EndSelection:<<<<<<<4 if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib)) { // Outlook ?? LOG.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front..."); - retrieveFormats = new string[] { DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF }; + retrieveFormats = new[] { DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF }; } else { - retrieveFormats = new string[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF }; + retrieveFormats = new[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF }; } foreach (string currentFormat in retrieveFormats) { if (formats.Contains(currentFormat)) { @@ -717,7 +717,7 @@ EndSelection:<<<<<<<4 /// string with format /// true if one the format is found public static bool ContainsFormat(string format) { - return ContainsFormat(GetDataObject(), new string[]{format}); + return ContainsFormat(GetDataObject(), new[]{format}); } /// @@ -726,7 +726,7 @@ EndSelection:<<<<<<<4 /// string with format /// true if one the format is found public static bool ContainsFormat(IDataObject dataObject, string format) { - return ContainsFormat(dataObject, new string[] { format }); + return ContainsFormat(dataObject, new[] { format }); } /// diff --git a/GreenshotPlugin/Core/CoreConfiguration.cs b/GreenshotPlugin/Core/CoreConfiguration.cs index b5bff9abb..6aa92b757 100644 --- a/GreenshotPlugin/Core/CoreConfiguration.cs +++ b/GreenshotPlugin/Core/CoreConfiguration.cs @@ -198,6 +198,9 @@ namespace GreenshotPlugin.Core { [IniProperty("OptimizeForRDP", Description="Make some optimizations for usage with remote desktop", DefaultValue="False")] public bool OptimizeForRDP; + [IniProperty("DisableRDPOptimizing", Description = "Disable all optimizations for usage with remote desktop", DefaultValue = "False")] + public bool DisableRDPOptimizing; + [IniProperty("MinimizeWorkingSetSize", Description="Optimize memory footprint, but with a performance penalty!", DefaultValue="False")] public bool MinimizeWorkingSetSize; diff --git a/GreenshotPlugin/Core/CredentialsHelper.cs b/GreenshotPlugin/Core/CredentialsHelper.cs index 5c9474b55..45280b538 100644 --- a/GreenshotPlugin/Core/CredentialsHelper.cs +++ b/GreenshotPlugin/Core/CredentialsHelper.cs @@ -102,7 +102,7 @@ namespace GreenshotPlugin.Core { Banner = banner; } - private bool _alwaysDisplay = false; + private bool _alwaysDisplay; /// /// Gets or sets if the dialog will be shown even if the credentials /// can be returned from an existing credential in the credential manager. @@ -138,7 +138,7 @@ namespace GreenshotPlugin.Core { } } - private bool _incorrectPassword = false; + private bool _incorrectPassword; /// Gets or sets if the incorrect password balloontip needs to be shown. Introduced AFTER Windows XPGets> public bool IncorrectPassword { get { @@ -149,7 +149,7 @@ namespace GreenshotPlugin.Core { } } - private bool _keepName = false; + private bool _keepName; /// Gets or sets if the name is read-only. public bool KeepName { get { @@ -200,7 +200,7 @@ namespace GreenshotPlugin.Core { } } - private bool _saveChecked = false; + private bool _saveChecked; /// Gets or sets if the save checkbox status. public bool SaveChecked { get { @@ -285,7 +285,7 @@ namespace GreenshotPlugin.Core { } } - private Image _banner = null; + private Image _banner; /// Gets or sets the image to display on the dialog. /// A null value will cause a system default image to be used. public Image Banner { diff --git a/GreenshotPlugin/Core/Effects.cs b/GreenshotPlugin/Core/Effects.cs index 70c45bfb9..d86e591fc 100644 --- a/GreenshotPlugin/Core/Effects.cs +++ b/GreenshotPlugin/Core/Effects.cs @@ -86,7 +86,8 @@ namespace Greenshot.Core { /// [TypeConverter(typeof(EffectConverter))] public class TornEdgeEffect : DropShadowEffect { - public TornEdgeEffect() : base() { + public TornEdgeEffect() + { Reset(); } public int ToothHeight { @@ -116,7 +117,7 @@ namespace Greenshot.Core { ToothHeight = 12; HorizontalToothRange = 20; VerticalToothRange = 20; - Edges = new bool[] { true, true, true, true }; + Edges = new[] { true, true, true, true }; GenerateShadow = true; } public override Image Apply(Image sourceImage, Matrix matrix) { @@ -146,16 +147,16 @@ namespace Greenshot.Core { /// MonochromeEffect /// public class MonochromeEffect : IEffect { - private byte threshold; + private readonly byte _threshold; /// Threshold for monochrome filter (0 - 255), lower value means less black public MonochromeEffect(byte threshold) { - this.threshold = threshold; + _threshold = threshold; } public void Reset() { // TODO: Modify the threshold to have a default, which is reset here } public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.CreateMonochrome(sourceImage, threshold); + return ImageHelper.CreateMonochrome(sourceImage, _threshold); } } @@ -163,7 +164,8 @@ namespace Greenshot.Core { /// AdjustEffect /// public class AdjustEffect : IEffect { - public AdjustEffect() : base() { + public AdjustEffect() + { Reset(); } public float Contrast { @@ -192,8 +194,9 @@ namespace Greenshot.Core { /// ReduceColorsEffect /// public class ReduceColorsEffect : IEffect { - private static ILog LOG = LogManager.GetLogger(typeof(ReduceColorsEffect)); - public ReduceColorsEffect() : base() { + private static readonly ILog LOG = LogManager.GetLogger(typeof(ReduceColorsEffect)); + public ReduceColorsEffect() + { Reset(); } public int Colors { @@ -355,9 +358,10 @@ namespace Greenshot.Core { public class EffectConverter : TypeConverter { // Fix to prevent BUG-1753 - private NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); + private readonly NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); - public EffectConverter() : base() { + public EffectConverter() + { numberFormatInfo.NumberDecimalSeparator = "."; numberFormatInfo.NumberGroupSeparator = ","; } @@ -382,7 +386,7 @@ namespace Greenshot.Core { return base.CanConvertTo(context, destinationType); } - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { // to string if (destinationType == typeof(string)) { StringBuilder sb = new StringBuilder(); @@ -400,7 +404,7 @@ namespace Greenshot.Core { } } // from string - if (value.GetType() == typeof(string)) { + if (value is string) { string settings = value as string; if (destinationType == typeof(DropShadowEffect)) { DropShadowEffect effect = new DropShadowEffect(); @@ -417,14 +421,13 @@ namespace Greenshot.Core { return base.ConvertTo(context, culture, value, destinationType); } - public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - if (value != null && value.GetType() == typeof(string)) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { + if (value != null && value is string) { string settings = value as string; if (settings.Contains("ToothHeight")) { return ConvertTo(context, culture, value, typeof(TornEdgeEffect)); - } else { - return ConvertTo(context, culture, value, typeof(DropShadowEffect)); } + return ConvertTo(context, culture, value, typeof(DropShadowEffect)); } return base.ConvertFrom(context, culture, value); } diff --git a/GreenshotPlugin/Core/EventDelay.cs b/GreenshotPlugin/Core/EventDelay.cs index 848d19dd9..1dbd3d7c7 100644 --- a/GreenshotPlugin/Core/EventDelay.cs +++ b/GreenshotPlugin/Core/EventDelay.cs @@ -23,8 +23,8 @@ using System; namespace GreenshotPlugin.Core { public class EventDelay { - private long lastCheck = 0; - private long waitTime; + private long lastCheck; + private readonly long waitTime; public EventDelay(long ticks) { this.waitTime = ticks; } diff --git a/GreenshotPlugin/Core/FastBitmap.cs b/GreenshotPlugin/Core/FastBitmap.cs index 228e1e4bf..8090a7b29 100644 --- a/GreenshotPlugin/Core/FastBitmap.cs +++ b/GreenshotPlugin/Core/FastBitmap.cs @@ -322,7 +322,7 @@ namespace GreenshotPlugin.Core { protected BitmapData bmData; protected int stride; /* bytes per pixel row */ - protected bool bitsLocked = false; + protected bool bitsLocked; protected byte* pointer; public static IFastBitmap Create(Bitmap source) { @@ -726,8 +726,8 @@ namespace GreenshotPlugin.Core { /// public unsafe class FastChunkyBitmap : FastBitmap { // Used for indexed images - private Color[] colorEntries; - private Dictionary colorCache = new Dictionary(); + private readonly Color[] colorEntries; + private readonly Dictionary colorCache = new Dictionary(); public FastChunkyBitmap(Bitmap source, Rectangle area) : base(source, area) { colorEntries = bitmap.Palette.Entries; diff --git a/GreenshotPlugin/Core/FilenameHelper.cs b/GreenshotPlugin/Core/FilenameHelper.cs index 30c7b3f59..236f4f2d9 100644 --- a/GreenshotPlugin/Core/FilenameHelper.cs +++ b/GreenshotPlugin/Core/FilenameHelper.cs @@ -41,7 +41,7 @@ namespace GreenshotPlugin.Core { private static readonly Regex SPLIT_REGEXP = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled); private const int MAX_TITLE_LENGTH = 80; - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const string UNSAFE_REPLACEMENT = "_"; /// @@ -159,7 +159,7 @@ namespace GreenshotPlugin.Core { switch (parameter.Substring(0, 1)) { // Padding p[,pad-character] case "p": - string[] padParams = parameter.Substring(1).Split(new char[] { ',' }); + string[] padParams = parameter.Substring(1).Split(new[] { ',' }); try { padWidth = int.Parse(padParams[0]); } catch { @@ -171,7 +171,7 @@ namespace GreenshotPlugin.Core { // replace // r, case "r": - string[] replaceParameters = parameter.Substring(1).Split(new char[] { ',' }); + string[] replaceParameters = parameter.Substring(1).Split(new[] { ',' }); if (replaceParameters != null && replaceParameters.Length == 2) { replacements.Add(replaceParameters[0], replaceParameters[1]); } @@ -191,7 +191,7 @@ namespace GreenshotPlugin.Core { // s[,length] case "s": string range = parameter.Substring(1); - string[] rangelist = range.Split(new char[] { ',' }); + string[] rangelist = range.Split(new[] { ',' }); if (rangelist.Length > 0) { try { startIndex = int.Parse(rangelist[0]); @@ -418,9 +418,9 @@ namespace GreenshotPlugin.Core { } return VAR_REGEXP.Replace(pattern, - new MatchEvaluator(delegate(Match m) { - return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); - }) + delegate(Match m) { + return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); + } ); } @@ -455,9 +455,9 @@ namespace GreenshotPlugin.Core { try { return VAR_REGEXP.Replace(pattern, - new MatchEvaluator(delegate(Match m) { - return MatchVarEvaluator(m, captureDetails, processVars, userVars, machineVars, filenameSafeMode); - }) + delegate(Match m) { + return MatchVarEvaluator(m, captureDetails, processVars, userVars, machineVars, filenameSafeMode); + } ); } catch (Exception e) { // adding additional data for bug tracking diff --git a/GreenshotPlugin/Core/GreenshotResources.cs b/GreenshotPlugin/Core/GreenshotResources.cs index 701786e80..216c82179 100644 --- a/GreenshotPlugin/Core/GreenshotResources.cs +++ b/GreenshotPlugin/Core/GreenshotResources.cs @@ -26,7 +26,7 @@ namespace GreenshotPlugin.Core { /// Centralized storage of the icons & bitmaps /// public static class GreenshotResources { - private static ComponentResourceManager greenshotResources = new ComponentResourceManager(typeof(GreenshotResources)); + private static readonly ComponentResourceManager greenshotResources = new ComponentResourceManager(typeof(GreenshotResources)); public static Image getImage(string imageName) { return (Image)greenshotResources.GetObject(imageName); diff --git a/GreenshotPlugin/Core/ImageHelper.cs b/GreenshotPlugin/Core/ImageHelper.cs index 86abd0dab..bad73adb5 100644 --- a/GreenshotPlugin/Core/ImageHelper.cs +++ b/GreenshotPlugin/Core/ImageHelper.cs @@ -24,10 +24,8 @@ using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; -using System.Runtime.InteropServices; using Greenshot.IniFile; using GreenshotPlugin.UnmanagedHelpers; -using Greenshot.Plugin; using Greenshot.Core; using log4net; @@ -48,8 +46,8 @@ namespace GreenshotPlugin.Core { /// Description of ImageHelper. /// public static class ImageHelper { - private static ILog LOG = LogManager.GetLogger(typeof(ImageHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageHelper)); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const int EXIF_ORIENTATION_ID = 0x0112; /// @@ -827,7 +825,7 @@ namespace GreenshotPlugin.Core { if ((shadowSize & 1) == 0) { shadowSize++; } - bool useGDIBlur = GDIplus.isBlurPossible(shadowSize); + bool useGDIBlur = GDIplus.IsBlurPossible(shadowSize); // Create "mask" for the shadow ColorMatrix maskMatrix = new ColorMatrix(); maskMatrix.Matrix00 = 0; @@ -1021,12 +1019,13 @@ namespace GreenshotPlugin.Core { public static ImageAttributes CreateAdjustAttributes(float brightness, float contrast, float gamma) { float adjustedBrightness = brightness - 1.0f; ColorMatrix applyColorMatrix = new ColorMatrix( - new float[][] { - new float[] {contrast, 0, 0, 0, 0}, // scale red - new float[] {0, contrast, 0, 0, 0}, // scale green - new float[] {0, 0, contrast, 0, 0}, // scale blue - new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha - new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1} + new[] + { + new[] {contrast, 0, 0, 0, 0}, // scale red + new[] {0, contrast, 0, 0, 0}, // scale green + new[] {0, 0, contrast, 0, 0}, // scale blue + new[] {0, 0, 0, 1.0f, 0}, // don't scale alpha + new[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1} }); //create some image attributes @@ -1063,10 +1062,11 @@ namespace GreenshotPlugin.Core { /// Bitmap with grayscale public static Image CreateGrayscale(Image sourceImage) { Bitmap clone = (Bitmap)Clone(sourceImage); - ColorMatrix grayscaleMatrix = new ColorMatrix( new float[][] { - new float[] {.3f, .3f, .3f, 0, 0}, - new float[] {.59f, .59f, .59f, 0, 0}, - new float[] {.11f, .11f, .11f, 0, 0}, + ColorMatrix grayscaleMatrix = new ColorMatrix( new[] + { + new[] {.3f, .3f, .3f, 0, 0}, + new[] {.59f, .59f, .59f, 0, 0}, + new[] {.11f, .11f, .11f, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); diff --git a/GreenshotPlugin/Core/ImageOutput.cs b/GreenshotPlugin/Core/ImageOutput.cs index 9b961b0f3..cc7a16af5 100644 --- a/GreenshotPlugin/Core/ImageOutput.cs +++ b/GreenshotPlugin/Core/ImageOutput.cs @@ -44,7 +44,7 @@ namespace GreenshotPlugin.Core { private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageOutput)); private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131; - private static Cache tmpFileCache = new Cache(10 * 60 * 60, RemoveExpiredTmpFile); + private static readonly Cache tmpFileCache = new Cache(10 * 60 * 60, RemoveExpiredTmpFile); /// /// Creates a PropertyItem (Metadata) to store with the image. diff --git a/GreenshotPlugin/Core/InterfaceUtils.cs b/GreenshotPlugin/Core/InterfaceUtils.cs index 0b02a9103..4b8710924 100644 --- a/GreenshotPlugin/Core/InterfaceUtils.cs +++ b/GreenshotPlugin/Core/InterfaceUtils.cs @@ -30,7 +30,7 @@ namespace GreenshotPlugin.Core { /// Description of InterfaceUtils. /// public static class InterfaceUtils { - private static ILog LOG = LogManager.GetLogger(typeof(InterfaceUtils)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(InterfaceUtils)); public static List GetSubclassesOf(Type type, bool excludeSystemTypes) { List list = new List(); diff --git a/GreenshotPlugin/Core/JSONHelper.cs b/GreenshotPlugin/Core/JSONHelper.cs index 8bb4e3625..1770e5657 100644 --- a/GreenshotPlugin/Core/JSONHelper.cs +++ b/GreenshotPlugin/Core/JSONHelper.cs @@ -8,7 +8,6 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; -using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; diff --git a/GreenshotPlugin/Core/Language.cs b/GreenshotPlugin/Core/Language.cs index e897c6a66..67899f1ed 100644 --- a/GreenshotPlugin/Core/Language.cs +++ b/GreenshotPlugin/Core/Language.cs @@ -35,21 +35,21 @@ namespace GreenshotPlugin.Core { /// The language resources are loaded from the language files found on fixed or supplied paths /// public class Language { - private static ILog LOG = LogManager.GetLogger(typeof(Language)); - private static List languagePaths = new List(); - private static IDictionary> languageFiles = new Dictionary>(); - private static IDictionary helpFiles = new Dictionary(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(Language)); + private static readonly List languagePaths = new List(); + private static readonly IDictionary> languageFiles = new Dictionary>(); + private static readonly IDictionary helpFiles = new Dictionary(); private const string DEFAULT_LANGUAGE = "en-US"; private const string HELP_FILENAME_PATTERN = @"help-*.html"; private const string LANGUAGE_FILENAME_PATTERN = @"language*.xml"; - private static Regex PREFIX_REGEXP = new Regex(@"language_([a-zA-Z0-9]+).*"); - private static Regex IETF_CLEAN_REGEXP = new Regex(@"[^a-zA-Z]+"); - private static Regex IETF_REGEXP = new Regex(@"^.*([a-zA-Z]{2}-[a-zA-Z]{2})\.xml$"); + private static readonly Regex PREFIX_REGEXP = new Regex(@"language_([a-zA-Z0-9]+).*"); + private static readonly Regex IETF_CLEAN_REGEXP = new Regex(@"[^a-zA-Z]+"); + private static readonly Regex IETF_REGEXP = new Regex(@"^.*([a-zA-Z]{2}-[a-zA-Z]{2})\.xml$"); private const string LANGUAGE_GROUPS_KEY = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups"; - private static List unsupportedLanguageGroups = new List(); - private static IDictionary resources = new Dictionary(); - private static string currentLanguage = null; - private static CoreConfiguration coreConfig = null; + private static readonly List unsupportedLanguageGroups = new List(); + private static readonly IDictionary resources = new Dictionary(); + private static string currentLanguage; + private static readonly CoreConfiguration coreConfig; public static event LanguageChangedHandler LanguageChanged; diff --git a/GreenshotPlugin/Core/LogHelper.cs b/GreenshotPlugin/Core/LogHelper.cs index 253493f58..27b2b6211 100644 --- a/GreenshotPlugin/Core/LogHelper.cs +++ b/GreenshotPlugin/Core/LogHelper.cs @@ -37,7 +37,7 @@ namespace GreenshotPlugin.Core { public class LogHelper { private const string LOG4NET_FILE = "log4net.xml"; private const string LOG4NET_PORTABLE_FILE = "log4net-portable.xml"; - private static bool isLog4NetConfigured = false; + private static bool isLog4NetConfigured; private const string INIT_MESSAGE = "Greenshot initialization of log system failed"; public static bool isInitialized { get { diff --git a/GreenshotPlugin/Core/NetworkHelper.cs b/GreenshotPlugin/Core/NetworkHelper.cs index dc816eab7..5a9ec8877 100644 --- a/GreenshotPlugin/Core/NetworkHelper.cs +++ b/GreenshotPlugin/Core/NetworkHelper.cs @@ -552,10 +552,10 @@ namespace GreenshotPlugin.Core { /// A container to supply files to a Multi-part form data upload /// public class ByteContainer : IBinaryContainer { - private byte[] file; - private string fileName; - private string contentType; - private int fileSize; + private readonly byte[] file; + private readonly string fileName; + private readonly string contentType; + private readonly int fileSize; public ByteContainer(byte[] file) : this(file, null) { } public ByteContainer(byte[] file, string filename) : this(file, filename, null) { @@ -635,9 +635,9 @@ namespace GreenshotPlugin.Core { /// A container to supply images to a Multi-part form data upload /// public class BitmapContainer : IBinaryContainer { - private Bitmap bitmap; - private SurfaceOutputSettings outputSettings; - private string fileName; + private readonly Bitmap bitmap; + private readonly SurfaceOutputSettings outputSettings; + private readonly string fileName; public BitmapContainer(Bitmap bitmap, SurfaceOutputSettings outputSettings, string filename) { this.bitmap = bitmap; @@ -712,9 +712,9 @@ namespace GreenshotPlugin.Core { /// A container to supply surfaces to a Multi-part form data upload /// public class SurfaceContainer : IBinaryContainer { - private ISurface surface; - private SurfaceOutputSettings outputSettings; - private string fileName; + private readonly ISurface surface; + private readonly SurfaceOutputSettings outputSettings; + private readonly string fileName; public SurfaceContainer(ISurface surface, SurfaceOutputSettings outputSettings, string filename) { this.surface = surface; diff --git a/GreenshotPlugin/Core/OAuthHelper.cs b/GreenshotPlugin/Core/OAuthHelper.cs index 110736f5e..add088da2 100644 --- a/GreenshotPlugin/Core/OAuthHelper.cs +++ b/GreenshotPlugin/Core/OAuthHelper.cs @@ -27,7 +27,6 @@ using System.Collections.Specialized; using System.Diagnostics; using System.Drawing; using System.Globalization; -using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; @@ -968,7 +967,7 @@ Greenshot received information from CloudServiceName. You can close this browser private string _cloudServiceName; - private IDictionary _returnValues = new Dictionary(); + private readonly IDictionary _returnValues = new Dictionary(); /// @@ -991,7 +990,7 @@ Greenshot received information from CloudServiceName. You can close this browser Process.Start(authorizationUrl); // Wait to get the authorization code response. - var context = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); + var context = listener.BeginGetContext(ListenerCallback, listener); _ready.Reset(); while (!context.AsyncWaitHandle.WaitOne(1000, true)) { diff --git a/GreenshotPlugin/Core/PluginUtils.cs b/GreenshotPlugin/Core/PluginUtils.cs index 122fbc150..a3d910e61 100644 --- a/GreenshotPlugin/Core/PluginUtils.cs +++ b/GreenshotPlugin/Core/PluginUtils.cs @@ -37,9 +37,9 @@ namespace GreenshotPlugin.Core { /// public static class PluginUtils { private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginUtils)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const string PATH_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"; - private static IDictionary exeIconCache = new Dictionary(); + private static readonly IDictionary exeIconCache = new Dictionary(); static PluginUtils() { conf.PropertyChanged += OnIconSizeChanged; diff --git a/GreenshotPlugin/Core/QuantizerHelper.cs b/GreenshotPlugin/Core/QuantizerHelper.cs index d9bfa1713..d2feec81e 100644 --- a/GreenshotPlugin/Core/QuantizerHelper.cs +++ b/GreenshotPlugin/Core/QuantizerHelper.cs @@ -71,7 +71,7 @@ namespace GreenshotPlugin.Core { } public class WuQuantizer : IDisposable { - private static ILog LOG = LogManager.GetLogger(typeof(WuQuantizer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(WuQuantizer)); private const Int32 MAXCOLOR = 512; private const Int32 RED = 2; @@ -82,23 +82,23 @@ namespace GreenshotPlugin.Core { private const Int32 MAXVOLUME = SIDESIZE * SIDESIZE * SIDESIZE; // To count the colors - private int colorCount = 0; + private readonly int colorCount; private Int32[] reds; private Int32[] greens; private Int32[] blues; private Int32[] sums; - private Int64[, ,] weights; - private Int64[, ,] momentsRed; - private Int64[, ,] momentsGreen; - private Int64[, ,] momentsBlue; - private Single[, ,] moments; + private readonly Int64[, ,] weights; + private readonly Int64[, ,] momentsRed; + private readonly Int64[, ,] momentsGreen; + private readonly Int64[, ,] momentsBlue; + private readonly Single[, ,] moments; private byte[] tag; - private WuColorCube[] cubes; - private Bitmap sourceBitmap; + private readonly WuColorCube[] cubes; + private readonly Bitmap sourceBitmap; private Bitmap resultBitmap; public void Dispose() { diff --git a/GreenshotPlugin/Core/SourceForgeHelper.cs b/GreenshotPlugin/Core/SourceForgeHelper.cs index 3a027cbbb..6ead257d0 100644 --- a/GreenshotPlugin/Core/SourceForgeHelper.cs +++ b/GreenshotPlugin/Core/SourceForgeHelper.cs @@ -21,7 +21,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Net; using System.Text.RegularExpressions; using System.Xml; @@ -96,7 +95,7 @@ namespace GreenshotPlugin.Core { /// Description of SourceForgeHelper. /// public class SourceForgeHelper { - private static ILog LOG = LogManager.GetLogger(typeof(SourceForgeHelper)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(SourceForgeHelper)); private const string RSSFEED = "http://getgreenshot.org/project-feed/"; /// diff --git a/GreenshotPlugin/Core/StringExtensions.cs b/GreenshotPlugin/Core/StringExtensions.cs index 9cbec97b4..6f457d212 100644 --- a/GreenshotPlugin/Core/StringExtensions.cs +++ b/GreenshotPlugin/Core/StringExtensions.cs @@ -26,7 +26,6 @@ using System.Text; using log4net; using System.Text.RegularExpressions; using System.Collections.Generic; -using System.Reflection; namespace GreenshotPlugin.Core { public static class StringExtensions { diff --git a/GreenshotPlugin/Core/WindowCapture.cs b/GreenshotPlugin/Core/WindowCapture.cs index a85792162..ebda0a660 100644 --- a/GreenshotPlugin/Core/WindowCapture.cs +++ b/GreenshotPlugin/Core/WindowCapture.cs @@ -62,7 +62,7 @@ namespace GreenshotPlugin.Core { set; } - private Dictionary metaData = new Dictionary(); + private readonly Dictionary metaData = new Dictionary(); public Dictionary MetaData { get {return metaData;} } @@ -644,7 +644,7 @@ namespace GreenshotPlugin.Core { // capture.Image = capturedBitmap; // capture.Location = captureBounds.Location; - using (SafeWindowDCHandle desktopDCHandle = SafeWindowDCHandle.fromDesktop()) { + using (SafeWindowDCHandle desktopDCHandle = SafeWindowDCHandle.FromDesktop()) { if (desktopDCHandle.IsInvalid) { // Get Exception before the error is lost Exception exceptionToThrow = CreateCaptureException("desktopDCHandle", captureBounds); diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 4b69f88ad..412e018bc 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -47,7 +47,7 @@ namespace GreenshotPlugin.Core { /// public class WindowsEnumerator { #region Member Variables - private List items = null; + private List items; #endregion /// @@ -89,7 +89,7 @@ namespace GreenshotPlugin.Core { public WindowsEnumerator GetWindows(IntPtr hWndParent, string classname) { items = new List(); List windows = new List(); - User32.EnumChildWindows(hWndParent, new EnumWindowsProc(WindowEnum), IntPtr.Zero); + User32.EnumChildWindows(hWndParent, WindowEnum, IntPtr.Zero); bool hasParent = !IntPtr.Zero.Equals(hWndParent); string parentText = null; @@ -164,11 +164,11 @@ namespace GreenshotPlugin.Core { private const string METRO_APPLAUNCHER_CLASS = "ImmersiveLauncher"; private const string METRO_GUTTER_CLASS = "ImmersiveGutter"; - private static ILog LOG = LogManager.GetLogger(typeof(WindowDetails)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static List ignoreHandles = new List(); - private static List excludeProcessesFromFreeze = new List(); - private static IAppVisibility appVisibility = null; + private static readonly ILog LOG = LogManager.GetLogger(typeof(WindowDetails)); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly List ignoreHandles = new List(); + private static readonly List excludeProcessesFromFreeze = new List(); + private static readonly IAppVisibility appVisibility; static WindowDetails() { try { @@ -189,10 +189,10 @@ namespace GreenshotPlugin.Core { return ignoreHandles.Contains(handle); } - private List childWindows = null; + private List childWindows; private IntPtr parentHandle = IntPtr.Zero; - private WindowDetails parent = null; - private bool frozen = false; + private WindowDetails parent; + private bool frozen; public bool isApp { get { @@ -224,7 +224,7 @@ namespace GreenshotPlugin.Core { /// /// The window handle. /// - private IntPtr hWnd = IntPtr.Zero; + private readonly IntPtr hWnd = IntPtr.Zero; /// /// To allow items to be compared, the hash code @@ -588,7 +588,7 @@ namespace GreenshotPlugin.Core { } } - private string text = null; + private string text; /// /// Gets the window's title (caption) /// @@ -606,7 +606,7 @@ namespace GreenshotPlugin.Core { } } - private string className = null; + private string className; /// /// Gets the window's class name. /// @@ -755,7 +755,7 @@ namespace GreenshotPlugin.Core { } private Rectangle previousWindowRectangle = Rectangle.Empty; - private long lastWindowRectangleRetrieveTime = 0; + private long lastWindowRectangleRetrieveTime; private const long CACHE_TIME = TimeSpan.TicksPerSecond * 2; /// /// Gets the bounding rectangle of the window @@ -1515,7 +1515,7 @@ namespace GreenshotPlugin.Core { continue; } // Ignore some classes - List ignoreClasses = new List(new string[] { "Progman", "XLMAIN", "Button", "Dwm" }); //"MS-SDIa" + List ignoreClasses = new List(new[] { "Progman", "XLMAIN", "Button", "Dwm" }); //"MS-SDIa" if (ignoreClasses.Contains(window.ClassName)) { continue; } @@ -1585,7 +1585,7 @@ namespace GreenshotPlugin.Core { continue; } // Ignore some classes - List ignoreClasses = new List(new string[] { "Progman", "XLMAIN", "Button", "Dwm" }); //"MS-SDIa" + List ignoreClasses = new List(new[] { "Progman", "XLMAIN", "Button", "Dwm" }); //"MS-SDIa" if (ignoreClasses.Contains(window.ClassName)) { continue; } diff --git a/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs b/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs index eb5b399e2..dd9e8a2b8 100644 --- a/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs +++ b/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLCurrentStyle.cs b/GreenshotPlugin/IEInterop/IHTMLCurrentStyle.cs index 0bab7edf0..40d511c56 100644 --- a/GreenshotPlugin/IEInterop/IHTMLCurrentStyle.cs +++ b/GreenshotPlugin/IEInterop/IHTMLCurrentStyle.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument.cs b/GreenshotPlugin/IEInterop/IHTMLDocument.cs index 176b66fea..d89a81159 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument2.cs b/GreenshotPlugin/IEInterop/IHTMLDocument2.cs index a7a2e26e4..79de005d0 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument3.cs b/GreenshotPlugin/IEInterop/IHTMLDocument3.cs index 8d4825044..6d9f2c8ba 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument3.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument3.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument4.cs b/GreenshotPlugin/IEInterop/IHTMLDocument4.cs index 2ee041264..b78943ced 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument4.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument4.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument5.cs b/GreenshotPlugin/IEInterop/IHTMLDocument5.cs index 10c603d7d..124f595b5 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument5.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument5.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLElement.cs b/GreenshotPlugin/IEInterop/IHTMLElement.cs index 5bdf3bf6f..e87c73efb 100644 --- a/GreenshotPlugin/IEInterop/IHTMLElement.cs +++ b/GreenshotPlugin/IEInterop/IHTMLElement.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLElement2.cs b/GreenshotPlugin/IEInterop/IHTMLElement2.cs index 44a278179..0aa0092b6 100644 --- a/GreenshotPlugin/IEInterop/IHTMLElement2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLElement2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLElementCollection.cs b/GreenshotPlugin/IEInterop/IHTMLElementCollection.cs index 3a393c69c..4a82b7e99 100644 --- a/GreenshotPlugin/IEInterop/IHTMLElementCollection.cs +++ b/GreenshotPlugin/IEInterop/IHTMLElementCollection.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Collections; using System.Runtime.InteropServices; diff --git a/GreenshotPlugin/IEInterop/IHTMLFrameBase.cs b/GreenshotPlugin/IEInterop/IHTMLFrameBase.cs index a41922c14..015ce20af 100644 --- a/GreenshotPlugin/IEInterop/IHTMLFrameBase.cs +++ b/GreenshotPlugin/IEInterop/IHTMLFrameBase.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLFramesCollection2.cs b/GreenshotPlugin/IEInterop/IHTMLFramesCollection2.cs index 07c2fab8a..65a541060 100644 --- a/GreenshotPlugin/IEInterop/IHTMLFramesCollection2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLFramesCollection2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLRect.cs b/GreenshotPlugin/IEInterop/IHTMLRect.cs index 943081b03..0045087a5 100644 --- a/GreenshotPlugin/IEInterop/IHTMLRect.cs +++ b/GreenshotPlugin/IEInterop/IHTMLRect.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLScreen.cs b/GreenshotPlugin/IEInterop/IHTMLScreen.cs index f51807b0d..f2f50b8b8 100644 --- a/GreenshotPlugin/IEInterop/IHTMLScreen.cs +++ b/GreenshotPlugin/IEInterop/IHTMLScreen.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLScreen2.cs b/GreenshotPlugin/IEInterop/IHTMLScreen2.cs index 459aeb741..d354175e4 100644 --- a/GreenshotPlugin/IEInterop/IHTMLScreen2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLScreen2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLSelectionObject.cs b/GreenshotPlugin/IEInterop/IHTMLSelectionObject.cs index 43fb5434c..17bcd982c 100644 --- a/GreenshotPlugin/IEInterop/IHTMLSelectionObject.cs +++ b/GreenshotPlugin/IEInterop/IHTMLSelectionObject.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLStyle.cs b/GreenshotPlugin/IEInterop/IHTMLStyle.cs index 31433a84c..5c3928bb4 100644 --- a/GreenshotPlugin/IEInterop/IHTMLStyle.cs +++ b/GreenshotPlugin/IEInterop/IHTMLStyle.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLTxtRange.cs b/GreenshotPlugin/IEInterop/IHTMLTxtRange.cs index 21e2997b8..78206f573 100644 --- a/GreenshotPlugin/IEInterop/IHTMLTxtRange.cs +++ b/GreenshotPlugin/IEInterop/IHTMLTxtRange.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLWindow2.cs b/GreenshotPlugin/IEInterop/IHTMLWindow2.cs index 16e1fd9cc..7eb6dfc53 100644 --- a/GreenshotPlugin/IEInterop/IHTMLWindow2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLWindow2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLWindow3.cs b/GreenshotPlugin/IEInterop/IHTMLWindow3.cs index 0fb76e227..0ddf5bbc4 100644 --- a/GreenshotPlugin/IEInterop/IHTMLWindow3.cs +++ b/GreenshotPlugin/IEInterop/IHTMLWindow3.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLWindow4.cs b/GreenshotPlugin/IEInterop/IHTMLWindow4.cs index 276f2bc73..bde9d27d5 100644 --- a/GreenshotPlugin/IEInterop/IHTMLWindow4.cs +++ b/GreenshotPlugin/IEInterop/IHTMLWindow4.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IWebBrowser2.cs b/GreenshotPlugin/IEInterop/IWebBrowser2.cs index 00abda678..d53d8df5b 100644 --- a/GreenshotPlugin/IEInterop/IWebBrowser2.cs +++ b/GreenshotPlugin/IEInterop/IWebBrowser2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IniFile/IniConfig.cs b/GreenshotPlugin/IniFile/IniConfig.cs index a6bbfca12..0f9d7401d 100644 --- a/GreenshotPlugin/IniFile/IniConfig.cs +++ b/GreenshotPlugin/IniFile/IniConfig.cs @@ -28,7 +28,7 @@ using log4net; namespace Greenshot.IniFile { public class IniConfig { - private static ILog LOG = LogManager.GetLogger(typeof(IniConfig)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(IniConfig)); private const string INI_EXTENSION = ".ini"; private const string DEFAULTS_POSTFIX = "-defaults"; private const string FIXED_POSTFIX = "-fixed"; @@ -36,22 +36,22 @@ namespace Greenshot.IniFile { /// /// A lock object for the ini file saving /// - private static object iniLock = new object(); + private static readonly object iniLock = new object(); /// /// As the ini implementation is kept someone generic, for reusing, this holds the name of the application /// - private static string applicationName = null; + private static string applicationName; /// /// As the ini implementation is kept someone generic, for reusing, this holds the name of the configuration /// - private static string configName = null; + private static string configName; /// /// A Dictionary with all the sections stored by section name /// - private static Dictionary sectionMap = new Dictionary(); + private static readonly Dictionary sectionMap = new Dictionary(); /// /// A Dictionary with the properties for a section stored by section name @@ -61,17 +61,17 @@ namespace Greenshot.IniFile { /// /// A Dictionary with the fixed-properties for a section stored by section name /// - private static Dictionary> fixedProperties = null; + private static Dictionary> fixedProperties; /// /// Stores if we checked for portable /// - private static bool portableCheckMade = false; + private static bool portableCheckMade; /// /// Is the configuration portable (meaning we don't store it in the AppData directory) /// - private static bool portable = false; + private static bool portable; public static bool IsPortable { get { return portable; diff --git a/GreenshotPlugin/IniFile/IniReader.cs b/GreenshotPlugin/IniFile/IniReader.cs index 3447bf9db..205efc616 100644 --- a/GreenshotPlugin/IniFile/IniReader.cs +++ b/GreenshotPlugin/IniFile/IniReader.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Collections.Generic; using System.IO; using System.Text; @@ -28,7 +28,7 @@ namespace Greenshot.IniFile { private const string SECTION_START = "["; private const string SECTION_END = "]"; private const string COMMENT = ";"; - private static char[] ASSIGNMENT = new char[] { '=' }; + private static readonly char[] ASSIGNMENT = new[] { '=' }; /** * Read an ini file to a Dictionary, each key is a section and the value is a Dictionary with name and values. diff --git a/GreenshotPlugin/IniFile/IniSection.cs b/GreenshotPlugin/IniFile/IniSection.cs index 40aba49f9..4587ae8fb 100644 --- a/GreenshotPlugin/IniFile/IniSection.cs +++ b/GreenshotPlugin/IniFile/IniSection.cs @@ -34,9 +34,9 @@ namespace Greenshot.IniFile { protected static ILog LOG = LogManager.GetLogger(typeof(IniSection)); [NonSerialized] - private IDictionary values = new Dictionary(); + private readonly IDictionary values = new Dictionary(); [NonSerialized] - private IniSectionAttribute iniSectionAttribute = null; + private IniSectionAttribute iniSectionAttribute; public IniSectionAttribute IniSectionAttribute { get { if (iniSectionAttribute == null) { diff --git a/GreenshotPlugin/IniFile/IniValue.cs b/GreenshotPlugin/IniFile/IniValue.cs index c7fe99d01..9c2cee792 100644 --- a/GreenshotPlugin/IniFile/IniValue.cs +++ b/GreenshotPlugin/IniFile/IniValue.cs @@ -31,11 +31,11 @@ namespace Greenshot.IniFile { /// A container to be able to pass the value from a IniSection around. /// public class IniValue { - private static ILog LOG = LogManager.GetLogger(typeof(IniValue)); - private PropertyInfo propertyInfo; - private FieldInfo fieldInfo; - private IniSection containingIniSection; - private IniPropertyAttribute attributes; + private static readonly ILog LOG = LogManager.GetLogger(typeof(IniValue)); + private readonly PropertyInfo propertyInfo; + private readonly FieldInfo fieldInfo; + private readonly IniSection containingIniSection; + private readonly IniPropertyAttribute attributes; public IniValue(IniSection containingIniSection, PropertyInfo propertyInfo, IniPropertyAttribute iniPropertyAttribute) { this.containingIniSection = containingIniSection; @@ -216,7 +216,7 @@ namespace Greenshot.IniFile { // Get all the values. while ((bool)moveNext.Invoke(enumerator, null)) { var key = current.Invoke(enumerator, null); - var valueObject = item.GetValue(myValue, new object[] { key }); + var valueObject = item.GetValue(myValue, new[] { key }); // Write to ini file! writer.WriteLine("{0}.{1}={2}", attributes.Name, ConvertValueToString(valueType1, key, attributes.Separator), ConvertValueToString(valueType2, valueObject, attributes.Separator)); } @@ -293,7 +293,7 @@ namespace Greenshot.IniFile { LOG.Warn(ex); //LOG.Error("Problem converting " + stringValue + " to type " + type2.FullName, e); } - addMethodInfo.Invoke(dictionary, new object[] { newValue1, newValue2 }); + addMethodInfo.Invoke(dictionary, new[] { newValue1, newValue2 }); addedElements = true; } } @@ -370,7 +370,7 @@ namespace Greenshot.IniFile { string arraySeparator = separator; object list = Activator.CreateInstance(valueType); // Logic for List<> - string[] arrayValues = valueString.Split(new string[] { arraySeparator }, StringSplitOptions.None); + string[] arrayValues = valueString.Split(new[] { arraySeparator }, StringSplitOptions.None); if (arrayValues == null || arrayValues.Length == 0) { return list; } @@ -385,7 +385,7 @@ namespace Greenshot.IniFile { LOG.Warn("Problem converting " + arrayValue + " to type " + valueType.FullName, ex); } if (newValue != null) { - addMethodInfo.Invoke(list, new object[] { newValue }); + addMethodInfo.Invoke(list, new[] { newValue }); } } } @@ -394,7 +394,7 @@ namespace Greenshot.IniFile { //LOG.Debug("No convertor for " + fieldType.ToString()); if (valueType == typeof(object) && valueString.Length > 0) { //LOG.Debug("Parsing: " + valueString); - string[] values = valueString.Split(new Char[] { ':' }); + string[] values = valueString.Split(new[] { ':' }); //LOG.Debug("Type: " + values[0]); //LOG.Debug("Value: " + values[1]); Type fieldTypeForValue = Type.GetType(values[0], true); diff --git a/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs b/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs index 8c49e4e2d..0cebfc6b7 100644 --- a/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs +++ b/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs @@ -18,12 +18,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using System.Drawing; -using System.IO; -using System.Windows.Forms; -using GreenshotPlugin.Core; +using System.Drawing; +using System.Windows.Forms; namespace Greenshot.Plugin { /// diff --git a/GreenshotPlugin/Interfaces/Generic.cs b/GreenshotPlugin/Interfaces/Generic.cs index 73e6c2cf6..96283027a 100644 --- a/GreenshotPlugin/Interfaces/Generic.cs +++ b/GreenshotPlugin/Interfaces/Generic.cs @@ -20,7 +20,6 @@ */ using System; using System.Drawing; -using System.Drawing.Imaging; using System.Windows.Forms; using Greenshot.Plugin.Drawing; diff --git a/GreenshotPlugin/Interfaces/IDestination.cs b/GreenshotPlugin/Interfaces/IDestination.cs index e7da7eb9a..0377f5783 100644 --- a/GreenshotPlugin/Interfaces/IDestination.cs +++ b/GreenshotPlugin/Interfaces/IDestination.cs @@ -25,14 +25,14 @@ using System.Windows.Forms; namespace Greenshot.Plugin { public class ExportInformation { - private string uri = null; - private string filepath = null; + private string uri; + private string filepath; - private bool exportMade = false; - private string destinationDesignation = null; - private string destinationDescription = null; + private bool exportMade; + private readonly string destinationDesignation; + private string destinationDescription; - private string errorMessage = null; + private string errorMessage; public ExportInformation(string destinationDesignation, string destinationDescription) { this.destinationDesignation = destinationDesignation; diff --git a/GreenshotPlugin/Interfaces/IProcessor.cs b/GreenshotPlugin/Interfaces/IProcessor.cs index 40737888f..d69d4d378 100644 --- a/GreenshotPlugin/Interfaces/IProcessor.cs +++ b/GreenshotPlugin/Interfaces/IProcessor.cs @@ -19,9 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; namespace Greenshot.Plugin { /// diff --git a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs index b21963bf2..f075adc73 100644 --- a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs +++ b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs @@ -21,7 +21,6 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.IO; using System.Windows.Forms; using GreenshotPlugin.Core; @@ -76,10 +75,10 @@ namespace Greenshot.Plugin { public delegate void HotKeyHandler(); public class SurfaceOutputSettings { - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private bool reduceColors; private bool disableReduceColors; - private List effects = new List(); + private readonly List effects = new List(); public SurfaceOutputSettings() { disableReduceColors = false; diff --git a/GreenshotPlugin/Interop/Base.cs b/GreenshotPlugin/Interop/Base.cs index af344c6c2..16c4799fe 100644 --- a/GreenshotPlugin/Interop/Base.cs +++ b/GreenshotPlugin/Interop/Base.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace Greenshot.Interop { /// diff --git a/GreenshotPlugin/Interop/COMWrapper.cs b/GreenshotPlugin/Interop/COMWrapper.cs index 49c3e1d8d..e06aea399 100644 --- a/GreenshotPlugin/Interop/COMWrapper.cs +++ b/GreenshotPlugin/Interop/COMWrapper.cs @@ -55,12 +55,12 @@ namespace Greenshot.Interop { /// /// The type of which method calls are intercepted and executed on the COM object. /// - private readonly Type _InterceptType; + private readonly Type _interceptType; /// /// The humanly readable target name /// - private readonly string _TargetName; + private readonly string _targetName; #endregion [DllImport("ole32.dll")] @@ -341,8 +341,8 @@ namespace Greenshot.Interop { private COMWrapper(object comObject, Type type, string targetName) : base(type) { _COMObject = comObject; _COMType = comObject.GetType(); - _InterceptType = type; - _TargetName = targetName; + _interceptType = type; + _targetName = targetName; } #endregion @@ -354,7 +354,7 @@ namespace Greenshot.Interop { /// sure that the COM object is still cleaned up. /// ~COMWrapper() { - LOG.DebugFormat("Finalize {0}", _InterceptType.ToString()); + LOG.DebugFormat("Finalize {0}", _interceptType); Dispose(false); } @@ -375,13 +375,13 @@ namespace Greenshot.Interop { /// private void Dispose(bool disposing) { if (null != _COMObject) { - LOG.DebugFormat("Disposing {0}", _InterceptType.ToString()); + LOG.DebugFormat("Disposing {0}", _interceptType); if (Marshal.IsComObject(_COMObject)) { try { int count; do { count = Marshal.ReleaseComObject(_COMObject); - LOG.DebugFormat("RCW count for {0} now is {1}", _InterceptType.ToString(), count); + LOG.DebugFormat("RCW count for {0} now is {1}", _interceptType, count); } while (count > 0); } catch (Exception ex) { LOG.WarnFormat("Problem releasing COM object {0}", _COMType); @@ -406,7 +406,7 @@ namespace Greenshot.Interop { /// The full name of the intercepted type. /// public override string ToString() { - return _InterceptType.FullName; + return _interceptType.FullName; } /// @@ -485,11 +485,11 @@ namespace Greenshot.Interop { if (oldWrapper == null) { throw new ArgumentException("wrapper proxy was no COMWrapper"); } - if (oldWrapper._InterceptType.IsAssignableFrom(newType)) { - COMWrapper newWrapper = new COMWrapper(oldWrapper._COMObject, newType, oldWrapper._TargetName); + if (oldWrapper._interceptType.IsAssignableFrom(newType)) { + COMWrapper newWrapper = new COMWrapper(oldWrapper._COMObject, newType, oldWrapper._targetName); return (T)newWrapper.GetTransparentProxy(); } - throw new InvalidCastException(string.Format("{0} is not assignable from {1}", oldWrapper._InterceptType, newType)); + throw new InvalidCastException(string.Format("{0} is not assignable from {1}", oldWrapper._interceptType, newType)); } /// @@ -536,21 +536,21 @@ namespace Greenshot.Interop { LOG.InfoFormat("Type information for Type with name: {0}", type.Name); try { foreach (MemberInfo memberInfo in type.GetMembers()) { - LOG.InfoFormat("Member: {0};", memberInfo.ToString()); + LOG.InfoFormat("Member: {0};", memberInfo); } } catch (Exception memberException) { LOG.Error(memberException); } try { foreach (PropertyInfo propertyInfo in type.GetProperties()) { - LOG.InfoFormat("Property: {0};", propertyInfo.ToString()); + LOG.InfoFormat("Property: {0};", propertyInfo); } } catch (Exception propertyException) { LOG.Error(propertyException); } try { foreach (FieldInfo fieldInfo in type.GetFields()) { - LOG.InfoFormat("Field: {0};", fieldInfo.ToString()); + LOG.InfoFormat("Field: {0};", fieldInfo); } } catch (Exception fieldException) { LOG.Error(fieldException); @@ -570,13 +570,13 @@ namespace Greenshot.Interop { public override IMessage Invoke(IMessage myMessage) { IMethodCallMessage callMessage = myMessage as IMethodCallMessage; if (null == callMessage) { - LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType().ToString()); + LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType()); return null; } MethodInfo method = callMessage.MethodBase as MethodInfo; if (null == method) { - LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase.ToString()); + LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase); return null; } @@ -589,25 +589,15 @@ namespace Greenshot.Interop { BindingFlags flags = BindingFlags.InvokeMethod; int argCount = callMessage.ArgCount; - object invokeObject; - Type invokeType; - Type byValType; - - object[] args; - object arg; - COMWrapper[] originalArgs; - COMWrapper wrapper; - ParameterModifier[] argModifiers = null; ParameterInfo[] parameters = null; - ParameterInfo parameter; if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) { Dispose(); } else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType) { returnValue = ToString(); } else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType) { - returnValue = _InterceptType; + returnValue = _interceptType; } else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) { returnValue = GetHashCode(); } else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType) { @@ -621,9 +611,11 @@ namespace Greenshot.Interop { return new ReturnMessage(new ArgumentNullException("handler"), callMessage); } } else { - invokeObject = _COMObject; - invokeType = _COMType; + var invokeObject = _COMObject; + var invokeType = _COMType; + object[] args; + ParameterInfo parameter; if (methodName.StartsWith("get_")) { // Property Get methodName = methodName.Substring(4); @@ -657,6 +649,9 @@ namespace Greenshot.Interop { } // Un-wrap wrapped COM objects before passing to the method + Type byValType; + COMWrapper wrapper; + COMWrapper[] originalArgs; if (null == args || 0 == args.Length) { originalArgs = null; } else { @@ -677,7 +672,7 @@ namespace Greenshot.Interop { if (null == args[i]) { args[i] = new DispatchWrapper(null); } - } else if (typeof(Decimal) == byValType) { + } else if (typeof(decimal) == byValType) { // If we're passing a decimal value by reference, // we need to pass a CurrencyWrapper to avoid a // type mismatch exception. @@ -694,7 +689,7 @@ namespace Greenshot.Interop { break; } catch (InvalidComObjectException icoEx) { // Should assist BUG-1616 and others - LOG.WarnFormat("COM object {0} has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.", _InterceptType.FullName); + LOG.WarnFormat("COM object {0} has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.", _interceptType.FullName); return new ReturnMessage(icoEx, callMessage); } catch (Exception ex) { // Test for rejected @@ -703,13 +698,13 @@ namespace Greenshot.Interop { comEx = ex.InnerException as COMException; } if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == RPC_E_FAIL)) { - string destinationName = _TargetName; + string destinationName = _targetName; // Try to find a "catchy" name for the rejecting application if (destinationName != null && destinationName.Contains(".")) { - destinationName = destinationName.Substring(0, destinationName.IndexOf(".")); + destinationName = destinationName.Substring(0, destinationName.IndexOf(".", StringComparison.Ordinal)); } if (destinationName == null) { - destinationName = _InterceptType.FullName; + destinationName = _interceptType.FullName; } DialogResult result = MessageBox.Show(PluginUtils.Host.GreenshotForm, Language.GetFormattedString("com_rejected", destinationName), Language.GetString("com_rejected_title"), MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); if (result == DialogResult.OK) { @@ -726,7 +721,7 @@ namespace Greenshot.Interop { if (returnType.IsInterface) { // Wrap the returned value in an intercepting COM wrapper if (Marshal.IsComObject(returnValue)) { - returnValue = Wrap(returnValue, returnType, _TargetName); + returnValue = Wrap(returnValue, returnType, _targetName); } } else if (returnType.IsEnum) { // Convert to proper Enum type @@ -742,7 +737,7 @@ namespace Greenshot.Interop { continue; } - arg = args[i]; + var arg = args[i]; if (null == arg) { continue; } @@ -751,7 +746,7 @@ namespace Greenshot.Interop { wrapper = null; byValType = GetByValType(parameter.ParameterType); - if (typeof(Decimal) == byValType) { + if (typeof(decimal) == byValType) { if (arg is CurrencyWrapper) { arg = ((CurrencyWrapper)arg).WrappedObject; } @@ -766,7 +761,7 @@ namespace Greenshot.Interop { } if (null == wrapper) { - wrapper = new COMWrapper(arg, byValType, _TargetName); + wrapper = new COMWrapper(arg, byValType, _targetName); } arg = wrapper.GetTransparentProxy(); } @@ -787,7 +782,7 @@ namespace Greenshot.Interop { /// object to cast /// public bool CanCastTo(Type toType, object o) { - bool returnValue = _InterceptType.IsAssignableFrom(toType); + bool returnValue = _interceptType.IsAssignableFrom(toType); return returnValue; } diff --git a/GreenshotPlugin/Interop/ComProgIdAttribute.cs b/GreenshotPlugin/Interop/ComProgIdAttribute.cs index c2d9e1434..7a64b4814 100644 --- a/GreenshotPlugin/Interop/ComProgIdAttribute.cs +++ b/GreenshotPlugin/Interop/ComProgIdAttribute.cs @@ -26,7 +26,7 @@ namespace Greenshot.Interop { /// [AttributeUsage(AttributeTargets.Interface, Inherited = false, AllowMultiple = false)] public sealed class ComProgIdAttribute : Attribute { - private string _value; + private readonly string _value; /// /// Extracts the attribute from the specified type. diff --git a/GreenshotPlugin/Interop/IAppVisibility.cs b/GreenshotPlugin/Interop/IAppVisibility.cs index edcfcf915..8eb267376 100644 --- a/GreenshotPlugin/Interop/IAppVisibility.cs +++ b/GreenshotPlugin/Interop/IAppVisibility.cs @@ -20,7 +20,6 @@ */ using System; using System.Runtime.InteropServices; -using Greenshot.Interop; namespace Greenshot.Interop { // This is used for Windows 8 to see if the App Launcher is active diff --git a/GreenshotPlugin/Properties/AssemblyInfo.cs b/GreenshotPlugin/Properties/AssemblyInfo.cs index f4e66e2f6..b28bc45ab 100644 --- a/GreenshotPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotPlugin/Properties/AssemblyInfo.cs @@ -21,7 +21,6 @@ using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs b/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs index 9a3fbbaf4..481c979e7 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs @@ -19,13 +19,15 @@ * along with this program. If not, see . */ using System; +using System.Diagnostics.CodeAnalysis; namespace GreenshotPlugin.UnmanagedHelpers { /// /// Window Style Flags /// [Flags] - public enum WindowStyleFlags : long { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WindowStyleFlags : long { //WS_OVERLAPPED = 0x00000000, WS_POPUP = 0x80000000, WS_CHILD = 0x40000000, @@ -76,7 +78,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] - public enum ExtendedWindowStyleFlags : uint { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum ExtendedWindowStyleFlags : uint { WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_NOPARENTNOTIFY = 0x00000004, WS_EX_TOPMOST = 0x00000008, @@ -112,6 +115,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum WindowPlacementFlags : uint { // The coordinates of the minimized window may be specified. // This flag must be specified if the coordinates are set in the ptMinPosition member. @@ -123,6 +127,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { WPF_RESTORETOMAXIMIZED = 0x0002 } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ShowWindowCommand : uint { /// /// Hides the window and activates another window. @@ -149,7 +154,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { ShowMaximized = 3, /// /// Displays a window in its most recent size and position. This value - /// is similar to , except + /// is similar to , except /// the window is not actived. /// ShowNoActivate = 4, @@ -164,13 +169,13 @@ namespace GreenshotPlugin.UnmanagedHelpers { Minimize = 6, /// /// Displays the window as a minimized window. This value is similar to - /// , except the + /// , except the /// window is not activated. /// ShowMinNoActive = 7, /// /// Displays the window in its current size and position. This value is - /// similar to , except the + /// similar to , except the /// window is not activated. /// ShowNA = 8, @@ -194,7 +199,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { ForceMinimize = 11 } - public enum SYSCOLOR : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum SYSCOLOR + { SCROLLBAR = 0, BACKGROUND = 1, DESKTOP = 1, @@ -234,7 +241,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// ai_productions@verizon.net or osirisgothra@hotmail.com /// Obtained on pinvoke.net, please contribute your code to support the wiki! /// - public enum SystemMetric : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum SystemMetric + { /// /// Width of the screen of the primary display monitor, in pixels. This is the same values obtained by calling GetDeviceCaps as follows: GetDeviceCaps( hdcPrimaryMonitor, HORZRES). /// @@ -612,7 +621,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// SM_REMOTECONTROL=0x2001 } - + + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum RegionResult { REGION_ERROR = 0, REGION_NULLREGION = 1, @@ -621,6 +631,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } // See http://msdn.microsoft.com/en-us/library/aa969530(v=vs.85).aspx + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DWMWINDOWATTRIBUTE { DWMWA_NCRENDERING_ENABLED = 1, DWMWA_NCRENDERING_POLICY, @@ -639,7 +650,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { DWMWA_FREEZE_REPRESENTATION, // Since Windows 8 DWMWA_LAST } - + + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum GetWindowCommand : uint { GW_HWNDFIRST = 0, GW_HWNDLAST = 1, @@ -651,13 +663,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DWM_BB { Enable = 1, BlurRegion = 2, TransitionMaximized = 4 } - public enum ClassLongIndex : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum ClassLongIndex + { GCL_CBCLSEXTRA = -20, // the size, in bytes, of the extra memory associated with the class. Setting this value does not change the number of extra bytes already allocated. GCL_CBWNDEXTRA = -18, // the size, in bytes, of the extra window memory associated with each window in the class. Setting this value does not change the number of extra bytes already allocated. For information on how to access this memory, see SetWindowLong. GCL_HBRBACKGROUND = -10, // a handle to the background brush associated with the class. @@ -670,7 +685,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { GCL_WNDPROC = -24, // the address of the window procedure, or a handle representing the address of the window procedure. You must use the CallWindowProc function to call the window procedure. } - public enum WindowsMessages : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WindowsMessages + { WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DESTROY = 0x0002, @@ -877,7 +894,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { } // Get/Set WindowLong Enum See: http://msdn.microsoft.com/en-us/library/ms633591.aspx - public enum WindowLongIndex : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WindowLongIndex + { GWL_EXSTYLE = -20, // Sets a new extended window style. GWL_HINSTANCE = -6, // Sets a new application instance handle. GWL_ID = -12, // Sets a new identifier of the child window. The window cannot be a top-level window. @@ -888,7 +907,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { // See: http://msdn.microsoft.com/en-us/library/ms633545.aspx [Flags] - public enum WindowPos : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WindowPos + { SWP_ASYNCWINDOWPOS = 0x4000, // If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request. SWP_DEFERERASE = 0x2000, // Prevents generation of the WM_SYNCPAINT message. SWP_DRAWFRAME = 0x0020, // Draws a frame (defined in the window's class description) around the window. @@ -906,13 +927,18 @@ namespace GreenshotPlugin.UnmanagedHelpers { SWP_SHOWWINDOW = 0x0040 //Displays the window. } - public enum ScrollBarDirection : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum ScrollBarDirection + { SB_HORZ = 0, SB_VERT = 1, SB_CTL = 2, SB_BOTH = 3 } - public enum ScrollbarCommand : int { + + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum ScrollbarCommand + { SB_LINEUP = 0, // Scrolls one line up. SB_LINEDOWN = 1, // Scrolls one line down. SB_PAGEUP = 2, // Scrolls one page up. @@ -924,6 +950,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { SB_ENDSCROLL = 8 // Ends scroll. } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ScrollInfoMask { SIF_RANGE = 0x1, SIF_PAGE = 0x2, @@ -937,6 +964,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// See: http://www.pinvoke.net/default.aspx/Enums/SendMessageTimeoutFlags.html /// [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum SendMessageTimeoutFlags : uint { SMTO_NORMAL = 0x0, SMTO_BLOCK = 0x1, @@ -945,6 +973,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, @@ -962,7 +991,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// See: http://msdn.microsoft.com/en-us/library/aa909766.aspx /// [Flags] - public enum SoundFlags : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum SoundFlags + { SND_SYNC = 0x0000, // play synchronously (default) SND_ASYNC = 0x0001, // play asynchronously SND_NODEFAULT = 0x0002, // silence (!default) if sound not found @@ -979,6 +1010,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// Used by GDI32.GetDeviceCaps /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/dd144877%28v=vs.85%29.aspx /// + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DeviceCaps { /// /// Device driver version @@ -1147,7 +1179,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// Used for User32.SetWinEventHook /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/dd373640%28v=vs.85%29.aspx /// - public enum WinEventHookFlags : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WinEventHookFlags + { WINEVENT_SKIPOWNTHREAD = 1, WINEVENT_SKIPOWNPROCESS = 2, WINEVENT_OUTOFCONTEXT = 0, @@ -1158,6 +1192,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// Used for User32.SetWinEventHook /// See MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/dd318066%28v=vs.85%29.aspx /// + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum WinEvent : uint { EVENT_OBJECT_ACCELERATORCHANGE = 32786, EVENT_OBJECT_CREATE = 32768, @@ -1207,7 +1242,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// Used for User32.SetWinEventHook /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/dd373606%28v=vs.85%29.aspx#OBJID_WINDOW /// - public enum EventObjects : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum EventObjects + { OBJID_ALERT = -10, OBJID_CARET = -8, OBJID_CLIENT = -4, @@ -1223,6 +1260,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DesktopAccessRight : uint { DESKTOP_READOBJECTS = 0x00000001, DESKTOP_CREATEWINDOW = 0x00000002, diff --git a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs index f3e2aff3e..dd4c9d604 100644 --- a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs @@ -53,7 +53,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// SafeDeviceContextHandle public static SafeDeviceContextHandle GetSafeDeviceContext(this Graphics graphics) { - return SafeDeviceContextHandle.fromGraphics(graphics); + return SafeDeviceContextHandle.FromGraphics(graphics); } } @@ -77,10 +77,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A hbitmap SafeHandle implementation /// public class SafeHBitmapHandle : SafeObjectHandle { - [SecurityCritical] - private SafeHBitmapHandle() : base(true) { - } - [SecurityCritical] public SafeHBitmapHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -105,10 +101,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A dibsection SafeHandle implementation /// public class SafeDibSectionHandle : SafeObjectHandle { - [SecurityCritical] - private SafeDibSectionHandle() : base(true) { - } - [SecurityCritical] public SafeDibSectionHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -123,20 +115,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("gdi32", SetLastError = true)] private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); - private SafeHandle hdc; - - [SecurityCritical] - private SafeSelectObjectHandle() : base(true) { - } + private readonly SafeHandle _hdc; [SecurityCritical] public SafeSelectObjectHandle(SafeDCHandle hdc, SafeHandle newHandle) : base(true) { - this.hdc = hdc; + _hdc = hdc; SetHandle(SelectObject(hdc.DangerousGetHandle(), newHandle.DangerousGetHandle())); } protected override bool ReleaseHandle() { - SelectObject(hdc.DangerousGetHandle(), handle); + SelectObject(_hdc.DangerousGetHandle(), handle); return true; } } @@ -153,10 +141,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteDC(IntPtr hDC); - [SecurityCritical] - private SafeCompatibleDCHandle() : base(true) { - } - [SecurityCritical] public SafeCompatibleDCHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -175,20 +159,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A DeviceContext SafeHandle implementation /// public class SafeDeviceContextHandle : SafeDCHandle { - private Graphics graphics = null; - - [SecurityCritical] - private SafeDeviceContextHandle() : base(true) { - } + private readonly Graphics _graphics; [SecurityCritical] public SafeDeviceContextHandle(Graphics graphics, IntPtr preexistingHandle) : base(true) { - this.graphics = graphics; + _graphics = graphics; SetHandle(preexistingHandle); } protected override bool ReleaseHandle() { - graphics.ReleaseHdc(handle); + _graphics.ReleaseHdc(handle); return true; } @@ -196,7 +176,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { return new SafeSelectObjectHandle(this, newHandle); } - public static SafeDeviceContextHandle fromGraphics(Graphics graphics) { + public static SafeDeviceContextHandle FromGraphics(Graphics graphics) { return new SafeDeviceContextHandle(graphics, graphics.GetHdc()); } } @@ -221,41 +201,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { public static extern uint GetPixel(SafeHandle hdc, int nXPos, int nYPos); [DllImport("gdi32", SetLastError=true)] public static extern int GetDeviceCaps(SafeHandle hdc, DeviceCaps nIndex); - - /// - /// StretchBlt extension for the graphics object - /// Doesn't work? - /// - /// - /// - public static void StretchBlt(this Graphics target, Bitmap sourceBitmap, Rectangle source, Rectangle destination) { - using (SafeDeviceContextHandle targetDC = target.GetSafeDeviceContext()) { - using (SafeCompatibleDCHandle safeCompatibleDCHandle = CreateCompatibleDC(targetDC)) { - using (SafeHBitmapHandle hBitmapHandle = new SafeHBitmapHandle(sourceBitmap.GetHbitmap())) { - using (safeCompatibleDCHandle.SelectObject(hBitmapHandle)) { - StretchBlt(targetDC, destination.X, destination.Y, destination.Width, destination.Height, safeCompatibleDCHandle, source.Left, source.Top, source.Width, source.Height, CopyPixelOperation.SourceCopy); - } - } - } - } - } - - /// - /// Bitblt extension for the graphics object - /// - /// - /// - public static void BitBlt(this Graphics target, Bitmap sourceBitmap, Rectangle source, Point destination, CopyPixelOperation rop) { - using (SafeDeviceContextHandle targetDC = target.GetSafeDeviceContext()) { - using (SafeCompatibleDCHandle safeCompatibleDCHandle = CreateCompatibleDC(targetDC)) { - using (SafeHBitmapHandle hBitmapHandle = new SafeHBitmapHandle(sourceBitmap.GetHbitmap())) { - using (safeCompatibleDCHandle.SelectObject(hBitmapHandle)) { - BitBlt(targetDC, destination.X, destination.Y, source.Width, source.Height, safeCompatibleDCHandle, source.Left, source.Top, rop); - } - } - } - } - } } [StructLayout(LayoutKind.Sequential, Pack = 2)] @@ -380,10 +325,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { bV5BlueMask = (uint)255; bV5AlphaMask = (uint)255 << 24; bV5CSType = 1934772034; // sRGB - bV5Endpoints = new CIEXYZTRIPLE(); - bV5Endpoints.ciexyzBlue = new CIEXYZ(0); - bV5Endpoints.ciexyzGreen = new CIEXYZ(0); - bV5Endpoints.ciexyzRed = new CIEXYZ(0); + bV5Endpoints = new CIEXYZTRIPLE + { + ciexyzBlue = new CIEXYZ(0), + ciexyzGreen = new CIEXYZ(0), + ciexyzRed = new CIEXYZ(0) + }; bV5GammaRed = 0; bV5GammaGreen = 0; bV5GammaBlue = 0; diff --git a/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs b/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs index dd446b425..ba0c86156 100644 --- a/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs +++ b/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs @@ -21,9 +21,7 @@ using System; using System.Drawing; using System.Runtime.InteropServices; -using System.Security; using log4net; -using Microsoft.Win32.SafeHandles; using System.Reflection; using System.Drawing.Drawing2D; using System.Drawing.Imaging; @@ -94,7 +92,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// GDIplus Helpers /// public static class GDIplus { - private static ILog LOG = LogManager.GetLogger(typeof(GDIplus)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(GDIplus)); [DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)] private static extern int GdipBitmapApplyEffect(IntPtr bitmap, IntPtr effect, ref RECT rectOfInterest, bool useAuxData, IntPtr auxData, int auxDataSize); @@ -107,7 +105,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { private static extern int GdipCreateEffect(Guid guid, out IntPtr effect); [DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)] private static extern int GdipDeleteEffect(IntPtr effect); - private static Guid BlurEffectGuid = new Guid("{633C80A4-1843-482B-9EF2-BE2834C5FDD4}"); + private static readonly Guid BlurEffectGuid = new Guid("{633C80A4-1843-482B-9EF2-BE2834C5FDD4}"); // Constant "FieldInfo" for getting the nativeImage from the Bitmap private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGE = typeof(Bitmap).GetField("nativeImage", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic); @@ -118,7 +116,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { // Constant "FieldInfo" for getting the nativeImageAttributes from the ImageAttributes private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGEATTRIBUTES = typeof(ImageAttributes).GetField("nativeImageAttributes", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic); - private static bool isBlurEnabled = Environment.OSVersion.Version.Major >= 6; + private static bool _isBlurEnabled = Environment.OSVersion.Version.Major >= 6; /// /// Get the nativeImage field from the bitmap /// @@ -173,10 +171,11 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// /// - public static bool isBlurPossible(int radius) { - if (!isBlurEnabled) { + public static bool IsBlurPossible(int radius) { + if (!_isBlurEnabled) { return false; - } else if (Environment.OSVersion.Version.Minor >= 2 && radius < 20) { + } + if (Environment.OSVersion.Version.Minor >= 2 && radius < 20) { return false; } return true; @@ -191,7 +190,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// bool true if the edges are expanded with the radius /// false if there is no GDI+ available or an exception occured public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radius, bool expandEdges) { - if (!isBlurPossible(radius)) { + if (!IsBlurPossible(radius)) { return false; } IntPtr hBlurParams = IntPtr.Zero; @@ -226,7 +225,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { // Everything worked, return true return true; } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem using GdipBitmapApplyEffect: ", ex); return false; } finally { @@ -240,7 +239,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { Marshal.FreeHGlobal(hBlurParams); } } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem cleaning up ApplyBlur: ", ex); } } @@ -251,7 +250,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// false if there is no GDI+ available or an exception occured public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle source, Matrix transform, ImageAttributes imageAttributes, int radius, bool expandEdges) { - if (!isBlurPossible(radius)) { + if (!IsBlurPossible(radius)) { return false; } @@ -291,7 +290,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { // Everything worked, return true return true; } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem using GdipDrawImageFX: ", ex); return false; } finally { @@ -305,7 +304,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { Marshal.FreeHGlobal(hBlurParams); } } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem cleaning up DrawWithBlur: ", ex); } } diff --git a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs index e74d38310..4da73b482 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs @@ -37,39 +37,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags); #region Structs - [StructLayout(LayoutKind.Sequential)] - private struct SHITEMID { - public ushort cb; - [MarshalAs(UnmanagedType.LPArray)] - public byte[] abID; - } - [StructLayout(LayoutKind.Sequential)] - private struct ITEMIDLIST { - public SHITEMID mkid; - } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - private struct BROWSEINFO { - public IntPtr hwndOwner; - public IntPtr pidlRoot; - public IntPtr pszDisplayName; - [MarshalAs(UnmanagedType.LPWStr)] - public string lpszTitle; - public uint ulFlags; - public IntPtr lpfn; - public int lParam; - public IntPtr iImage; - } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] private struct SHFILEINFO { - public IntPtr hIcon; - public int iIcon; - public uint dwAttributes; + public readonly IntPtr hIcon; + public readonly int iIcon; + public readonly uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - public string szDisplayName; + public readonly string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] - public string szTypeName; + public readonly string szTypeName; }; #endregion @@ -146,27 +123,27 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// Returns an icon for a given file extension - indicated by the name parameter. /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/bb762179(v=vs.85).aspx /// - /// Filename + /// Filename /// Large or small /// Whether to include the link icon /// System.Drawing.Icon public static Icon GetFileIcon(string filename, IconSize size, bool linkOverlay) { SHFILEINFO shfi = new SHFILEINFO(); // SHGFI_USEFILEATTRIBUTES makes it simulate, just gets the icon for the extension - uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES; + uint flags = SHGFI_ICON | SHGFI_USEFILEATTRIBUTES; - if (true == linkOverlay) { - flags += Shell32.SHGFI_LINKOVERLAY; + if (linkOverlay) { + flags += SHGFI_LINKOVERLAY; } // Check the size specified for return. if (IconSize.Small == size) { - flags += Shell32.SHGFI_SMALLICON; + flags += SHGFI_SMALLICON; } else { - flags += Shell32.SHGFI_LARGEICON; + flags += SHGFI_LARGEICON; } - SHGetFileInfo(Path.GetFileName(filename), Shell32.FILE_ATTRIBUTE_NORMAL, ref shfi, (uint)Marshal.SizeOf(shfi), flags); + SHGetFileInfo(Path.GetFileName(filename), FILE_ATTRIBUTE_NORMAL, ref shfi, (uint)Marshal.SizeOf(shfi), flags); // Only return an icon if we really got one if (shfi.hIcon != IntPtr.Zero) { diff --git a/GreenshotPlugin/UnmanagedHelpers/User32.cs b/GreenshotPlugin/UnmanagedHelpers/User32.cs index b3335a204..ef85d5994 100644 --- a/GreenshotPlugin/UnmanagedHelpers/User32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/User32.cs @@ -63,7 +63,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { #region DllImports [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - public extern static bool IsWindowVisible(IntPtr hWnd); + public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32", SetLastError = true)] public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); [DllImport("user32", SetLastError = true)] @@ -75,9 +75,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("user32", SetLastError = true)] public static extern int ShowWindow(IntPtr hWnd, ShowWindowCommand nCmdShow); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public extern static int GetWindowText(IntPtr hWnd, StringBuilder lpString, int cch); + public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int cch); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public extern static int GetWindowTextLength(IntPtr hWnd); + public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32", SetLastError = true)] public static extern uint GetSysColor(int nIndex); [DllImport("user32", SetLastError = true)] @@ -98,13 +98,13 @@ namespace GreenshotPlugin.UnmanagedHelpers { public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WindowPlacement lpwndpl); [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - public extern static bool IsIconic(IntPtr hWnd); + public static extern bool IsIconic(IntPtr hWnd); [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - public extern static bool IsZoomed(IntPtr hwnd); - [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public extern static int GetClassName (IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); + public static extern bool IsZoomed(IntPtr hwnd); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern int GetClassName (IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); + [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); @@ -112,13 +112,13 @@ namespace GreenshotPlugin.UnmanagedHelpers { [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); [DllImport("user32", CharSet=CharSet.Unicode, SetLastError=true)] - public extern static IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); + public static extern 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); + public static extern 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); + public static extern int GetWindowLong(IntPtr hwnd, int index); [DllImport("user32", SetLastError = true, EntryPoint = "GetWindowLongPtr")] - public extern static IntPtr GetWindowLongPtr(IntPtr hwnd, int nIndex); + public static extern IntPtr GetWindowLongPtr(IntPtr hwnd, int nIndex); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int SetWindowLong(IntPtr hWnd, int index, int styleFlags); [DllImport("user32", SetLastError = true, EntryPoint = "SetWindowLongPtr")] @@ -131,9 +131,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, IntPtr lParam); + public static extern int EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); [DllImport("user32", SetLastError = true)] - public extern static int EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); + public static extern 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); @@ -187,7 +187,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("user32", SetLastError = true, CharSet = CharSet.Unicode)] public static extern uint RegisterWindowMessage(string lpString); [DllImport("user32", SetLastError = true, CharSet = CharSet.Unicode)] - public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out UIntPtr lpdwResult); + public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out UIntPtr lpdwResult); [DllImport("user32", SetLastError = true)] private static extern bool GetPhysicalCursorPos(out POINT cursorLocation); [DllImport("user32", SetLastError=true)] @@ -359,9 +359,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A SafeHandle class implementation for the hIcon /// public class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid { - private SafeIconHandle() : base(true) { - } - public SafeIconHandle(IntPtr hIcon) : base(true) { SetHandle(hIcon); } @@ -381,24 +378,21 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("user32", SetLastError = true)] private static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC); - private IntPtr hWnd; - [SecurityCritical] - private SafeWindowDCHandle() : base(true) { - } + private readonly IntPtr _hWnd; [SecurityCritical] public SafeWindowDCHandle(IntPtr hWnd, IntPtr preexistingHandle) : base(true) { - this.hWnd = hWnd; + _hWnd = hWnd; SetHandle(preexistingHandle); } [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true)] protected override bool ReleaseHandle() { - bool returnValue = ReleaseDC(hWnd, handle); + bool returnValue = ReleaseDC(_hWnd, handle); return returnValue; } - public static SafeWindowDCHandle fromDesktop() { + public static SafeWindowDCHandle FromDesktop() { IntPtr hWndDesktop = User32.GetDesktopWindow(); IntPtr hDCDesktop = GetWindowDC(hWndDesktop); return new SafeWindowDCHandle(hWndDesktop, hDCDesktop);