diff --git a/Greenshot/App.config b/Greenshot/App.config index b3cdbf446..45f514c72 100644 --- a/Greenshot/App.config +++ b/Greenshot/App.config @@ -1,4 +1,4 @@ - + diff --git a/Greenshot/Configuration/AppConfig.cs b/Greenshot/Configuration/AppConfig.cs index f8a83ba68..de704ee91 100644 --- a/Greenshot/Configuration/AppConfig.cs +++ b/Greenshot/Configuration/AppConfig.cs @@ -28,8 +28,8 @@ using System.Windows.Forms; using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.Core; -using Greenshot.Plugin; using Greenshot.IniFile; +using log4net; namespace Greenshot.Configuration { public enum ScreenshotDestinations {Editor=1, FileDefault=2, FileWithDialog=4, Clipboard=8, Printer=16, EMail=32} @@ -42,7 +42,7 @@ namespace Greenshot.Configuration { /// [Serializable] public class AppConfig { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(AppConfig)); + private static ILog LOG = LogManager.GetLogger(typeof(AppConfig)); private static readonly Regex FIXOLD_REGEXP = new Regex(@"%(?[\w]+)%", RegexOptions.Compiled); private const string VAR_PREFIX = "${"; private const string VAR_POSTFIX = "}"; @@ -112,7 +112,7 @@ namespace Greenshot.Configuration { /// String with old syntax %VAR% /// The fixed pattern private static string FixFallback(string oldPattern) { - return FIXOLD_REGEXP.Replace(oldPattern, new MatchEvaluator(delegate(Match m) { return VAR_PREFIX + m.Groups["variable"].Value + VAR_POSTFIX;})); + return FIXOLD_REGEXP.Replace(oldPattern, delegate(Match m) { return VAR_PREFIX + m.Groups["variable"].Value + VAR_POSTFIX;}); } /// diff --git a/Greenshot/Configuration/LanguageKeys.cs b/Greenshot/Configuration/LanguageKeys.cs index 2d1d74314..fc08c50bc 100644 --- a/Greenshot/Configuration/LanguageKeys.cs +++ b/Greenshot/Configuration/LanguageKeys.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 Greenshot.Configuration { public enum LangKey { diff --git a/Greenshot/Configuration/RuntimeConfig.cs b/Greenshot/Configuration/RuntimeConfig.cs index be2b5176b..4d8330e94 100644 --- a/Greenshot/Configuration/RuntimeConfig.cs +++ b/Greenshot/Configuration/RuntimeConfig.cs @@ -18,11 +18,8 @@ * 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.Drawing; -using Greenshot.Plugin; +using System.Drawing; namespace Greenshot.Configuration { /// diff --git a/Greenshot/Controls/BindableToolStripButton.cs b/Greenshot/Controls/BindableToolStripButton.cs index cfbe27a92..5adb7506a 100644 --- a/Greenshot/Controls/BindableToolStripButton.cs +++ b/Greenshot/Controls/BindableToolStripButton.cs @@ -37,7 +37,7 @@ namespace Greenshot.Controls { } public BindableToolStripButton() :base() { - this.CheckedChanged += new EventHandler(BindableToolStripButton_CheckedChanged); + CheckedChanged += BindableToolStripButton_CheckedChanged; } void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) { diff --git a/Greenshot/Controls/BindableToolStripComboBox.cs b/Greenshot/Controls/BindableToolStripComboBox.cs index 0b9eb1b60..c49822242 100644 --- a/Greenshot/Controls/BindableToolStripComboBox.cs +++ b/Greenshot/Controls/BindableToolStripComboBox.cs @@ -37,7 +37,7 @@ namespace Greenshot.Controls { } public BindableToolStripComboBox() :base() { - this.SelectedIndexChanged += new EventHandler(BindableToolStripComboBox_SelectedIndexChanged); + SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; } void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) { diff --git a/Greenshot/Controls/ColorButton.cs b/Greenshot/Controls/ColorButton.cs index 6d8c70412..060b83592 100644 --- a/Greenshot/Controls/ColorButton.cs +++ b/Greenshot/Controls/ColorButton.cs @@ -40,7 +40,7 @@ namespace Greenshot.Controls { } public ColorButton() { - Click += new EventHandler(ColorButtonClick); + Click += ColorButtonClick; } public Color SelectedColor { @@ -71,7 +71,7 @@ namespace Greenshot.Controls { ColorDialog colorDialog = ColorDialog.GetInstance(); colorDialog.Color = SelectedColor; // Using the parent to make sure the dialog doesn't show on another window - colorDialog.ShowDialog(this.Parent.Parent); + colorDialog.ShowDialog(Parent.Parent); if (colorDialog.DialogResult != DialogResult.Cancel) { if (!colorDialog.Color.Equals(SelectedColor)) { SelectedColor = colorDialog.Color; diff --git a/Greenshot/Controls/FontFamilyComboBox.cs b/Greenshot/Controls/FontFamilyComboBox.cs index c2a772097..66d48ffd1 100644 --- a/Greenshot/Controls/FontFamilyComboBox.cs +++ b/Greenshot/Controls/FontFamilyComboBox.cs @@ -44,7 +44,7 @@ namespace Greenshot.Controls { { ComboBox.DataSource = FontFamily.Families; ComboBox.DisplayMember = "Name"; - this.SelectedIndexChanged += new EventHandler(BindableToolStripComboBox_SelectedIndexChanged); + SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; } void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) diff --git a/Greenshot/Controls/MenuStripEx.cs b/Greenshot/Controls/MenuStripEx.cs index ae72e310d..34feb6f0d 100644 --- a/Greenshot/Controls/MenuStripEx.cs +++ b/Greenshot/Controls/MenuStripEx.cs @@ -45,17 +45,17 @@ namespace Greenshot.Controls { /// public bool ClickThrough { get { - return this.clickThrough; + return clickThrough; } set { - this.clickThrough = value; + clickThrough = value; } } protected override void WndProc(ref Message m) { base.WndProc(ref m); - if (this.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 4f2219ada..04856b867 100644 --- a/Greenshot/Controls/NonJumpingPanel.cs +++ b/Greenshot/Controls/NonJumpingPanel.cs @@ -22,12 +22,16 @@ /// /// 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 { - public class NonJumpingPanel : System.Windows.Forms.Panel { - protected override System.Drawing.Point ScrollToControl(System.Windows.Forms.Control activeControl) { + public class NonJumpingPanel : Panel { + protected override Point ScrollToControl(Control activeControl) { // Returning the current location prevents the panel from // scrolling to the active control when the panel loses and regains focus - return this.DisplayRectangle.Location; + return DisplayRectangle.Location; } } } diff --git a/Greenshot/Controls/Pipette.cs b/Greenshot/Controls/Pipette.cs index 7bf57d0d8..c474c0f31 100644 --- a/Greenshot/Controls/Pipette.cs +++ b/Greenshot/Controls/Pipette.cs @@ -19,6 +19,7 @@ * along with this program. If not, see . */ using System; +using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using Greenshot.Forms; @@ -41,7 +42,7 @@ namespace Greenshot.Controls { public Pipette() { BorderStyle = BorderStyle.FixedSingle; dragging = false; - _image = (Bitmap)new System.ComponentModel.ComponentResourceManager(typeof(ColorDialog)).GetObject("pipette.Image"); + _image = (Bitmap)new ComponentResourceManager(typeof(ColorDialog)).GetObject("pipette.Image"); Image = _image; _cursor = CreateCursor((Bitmap)_image, 1, 14); movableShowColorForm = new MovableShowColorForm(); @@ -99,7 +100,7 @@ namespace Greenshot.Controls { /// MouseEventArgs protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { - User32.SetCapture(this.Handle); + User32.SetCapture(Handle); movableShowColorForm.MoveTo(PointToScreen(new Point(e.X, e.Y))); } base.OnMouseDown(e); @@ -136,7 +137,7 @@ namespace Greenshot.Controls { /// /// protected override void OnMouseCaptureChanged(EventArgs e) { - if (this.Capture) { + if (Capture) { dragging = true; Image = null; Cursor c = _cursor; diff --git a/Greenshot/Controls/ToolStripColorButton.cs b/Greenshot/Controls/ToolStripColorButton.cs index af00a2cdb..8bbc300e6 100644 --- a/Greenshot/Controls/ToolStripColorButton.cs +++ b/Greenshot/Controls/ToolStripColorButton.cs @@ -38,7 +38,7 @@ namespace Greenshot.Controls { private Color selectedColor = Color.Transparent; public ToolStripColorButton() { - Click+= new EventHandler(ColorButtonClick); + Click+= ColorButtonClick; } public Color SelectedColor { @@ -69,7 +69,7 @@ namespace Greenshot.Controls { ColorDialog colorDialog = ColorDialog.GetInstance(); colorDialog.Color = SelectedColor; // Using the parent to make sure the dialog doesn't show on another window - colorDialog.ShowDialog(this.Parent.Parent); + colorDialog.ShowDialog(Parent.Parent); if (colorDialog.DialogResult != DialogResult.Cancel) { if (!colorDialog.Color.Equals(SelectedColor)) { SelectedColor = colorDialog.Color; diff --git a/Greenshot/Controls/ToolStripEx.cs b/Greenshot/Controls/ToolStripEx.cs index 6c516354e..77a0b3959 100644 --- a/Greenshot/Controls/ToolStripEx.cs +++ b/Greenshot/Controls/ToolStripEx.cs @@ -46,17 +46,17 @@ namespace Greenshot.Controls { public bool ClickThrough { get { - return this.clickThrough; + return clickThrough; } set { - this.clickThrough = value; + clickThrough = value; } } protected override void WndProc(ref Message m) { base.WndProc(ref m); - if (this.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 cb606192d..5bcc1ad98 100644 --- a/Greenshot/Destinations/ClipboardDestination.cs +++ b/Greenshot/Destinations/ClipboardDestination.cs @@ -19,23 +19,21 @@ * along with this program. If not, see . */ using System; -using System.Collections.Generic; using System.Drawing; -using System.IO; using System.Windows.Forms; using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; -using Greenshot.Helpers; using Greenshot.IniFile; +using log4net; namespace Greenshot.Destinations { /// /// Description of ClipboardDestination. /// public class ClipboardDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ClipboardDestination)); + private static ILog LOG = LogManager.GetLogger(typeof(ClipboardDestination)); private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "Clipboard"; @@ -64,12 +62,12 @@ namespace Greenshot.Destinations { public override Image DisplayIcon { get { - return GreenshotPlugin.Core.GreenshotResources.getImage("Clipboard.Image"); + return GreenshotResources.getImage("Clipboard.Image"); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); try { ClipboardHelper.SetClipboardData(surface); exportInformation.ExportMade = true; diff --git a/Greenshot/Destinations/EditorDestination.cs b/Greenshot/Destinations/EditorDestination.cs index 757d4db6f..d5214eabc 100644 --- a/Greenshot/Destinations/EditorDestination.cs +++ b/Greenshot/Destinations/EditorDestination.cs @@ -21,27 +21,22 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.Drawing.Imaging; -using System.Drawing.Printing; -using System.IO; -using System.Windows.Forms; - using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; -using Greenshot.Helpers; using Greenshot.IniFile; +using log4net; namespace Greenshot.Destinations { /// /// Description of EditorDestination. /// public class EditorDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(EditorDestination)); + private static ILog LOG = LogManager.GetLogger(typeof(EditorDestination)); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); public const string DESIGNATION = "Editor"; private IImageEditor editor = null; - private static Image greenshotIcon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon().ToBitmap(); + private static Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap(); public EditorDestination() { } @@ -91,7 +86,7 @@ namespace Greenshot.Destinations { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); // Make sure we collect the garbage before opening the screenshot GC.Collect(); GC.WaitForPendingFinalizers(); diff --git a/Greenshot/Destinations/EmailDestination.cs b/Greenshot/Destinations/EmailDestination.cs index a33605611..fc1a9f849 100644 --- a/Greenshot/Destinations/EmailDestination.cs +++ b/Greenshot/Destinations/EmailDestination.cs @@ -19,10 +19,7 @@ * along with this program. If not, see . */ using System; -using System.Collections.Generic; using System.Drawing; -using System.IO; -using System.Text.RegularExpressions; using System.Windows.Forms; using Greenshot.Configuration; @@ -30,15 +27,16 @@ using Greenshot.Helpers; using Greenshot.Plugin; using GreenshotPlugin.Core; using Greenshot.IniFile; +using log4net; namespace Greenshot.Destinations { /// /// Description of EmailDestination. /// public class EmailDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(EmailDestination)); + private static ILog LOG = LogManager.GetLogger(typeof(EmailDestination)); private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static Image mailIcon = GreenshotPlugin.Core.GreenshotResources.getImage("Email.Image"); + private static Image mailIcon = GreenshotResources.getImage("Email.Image"); private static bool isActiveFlag = false; private static string mapiClient = null; public const string DESIGNATION = "EMail"; @@ -109,7 +107,7 @@ namespace Greenshot.Destinations { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); MapiMailMessage.SendImage(surface, captureDetails); exportInformation.ExportMade = true; ProcessExport(exportInformation, surface); diff --git a/Greenshot/Destinations/FileDestination.cs b/Greenshot/Destinations/FileDestination.cs index 9f61be625..8ba1c3a7c 100644 --- a/Greenshot/Destinations/FileDestination.cs +++ b/Greenshot/Destinations/FileDestination.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; @@ -27,16 +26,16 @@ using System.Windows.Forms; using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; -using Greenshot.Helpers; using Greenshot.IniFile; using GreenshotPlugin.Controls; +using log4net; namespace Greenshot.Destinations { /// /// Description of FileSaveAsDestination. /// public class FileDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(FileDestination)); + private static ILog LOG = LogManager.GetLogger(typeof(FileDestination)); private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "FileNoDialog"; @@ -66,12 +65,12 @@ namespace Greenshot.Destinations { public override Image DisplayIcon { get { - return GreenshotPlugin.Core.GreenshotResources.getImage("Save.Image"); + return GreenshotResources.getImage("Save.Image"); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); bool outputMade; bool overwrite; string fullPath; diff --git a/Greenshot/Destinations/FileWithDialogDestination.cs b/Greenshot/Destinations/FileWithDialogDestination.cs index e962c2737..c107cf8d7 100644 --- a/Greenshot/Destinations/FileWithDialogDestination.cs +++ b/Greenshot/Destinations/FileWithDialogDestination.cs @@ -18,24 +18,22 @@ * 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.Drawing; -using System.IO; using System.Windows.Forms; using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; -using Greenshot.Helpers; using Greenshot.IniFile; +using log4net; namespace Greenshot.Destinations { /// /// Description of FileWithDialog. /// public class FileWithDialogDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(FileWithDialogDestination)); + private static ILog LOG = LogManager.GetLogger(typeof(FileWithDialogDestination)); private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "FileDialog"; @@ -65,12 +63,12 @@ namespace Greenshot.Destinations { public override Image DisplayIcon { get { - return GreenshotPlugin.Core.GreenshotResources.getImage("Save.Image"); + return GreenshotResources.getImage("Save.Image"); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); string savedTo = null; // Bug #2918756 don't overwrite path if SaveWithDialog returns null! savedTo = ImageOutput.SaveWithDialog(surface, captureDetails); diff --git a/Greenshot/Destinations/PickerDestination.cs b/Greenshot/Destinations/PickerDestination.cs index f602167fe..49c284c77 100644 --- a/Greenshot/Destinations/PickerDestination.cs +++ b/Greenshot/Destinations/PickerDestination.cs @@ -18,25 +18,21 @@ * 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.Drawing; -using System.IO; -using System.Windows.Forms; +using System.Collections.Generic; using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; using Greenshot.Helpers; -using Greenshot.Forms; using Greenshot.IniFile; +using log4net; namespace Greenshot.Destinations { /// /// The PickerDestination shows a context menu with all possible destinations, so the user can "pick" one /// public class PickerDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PickerDestination)); + private static ILog LOG = LogManager.GetLogger(typeof(PickerDestination)); private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "Picker"; diff --git a/Greenshot/Destinations/PrinterDestination.cs b/Greenshot/Destinations/PrinterDestination.cs index 6719a86d9..b1867e74f 100644 --- a/Greenshot/Destinations/PrinterDestination.cs +++ b/Greenshot/Destinations/PrinterDestination.cs @@ -18,11 +18,10 @@ * 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.Drawing; using System.Drawing.Printing; -using System.IO; using System.Windows.Forms; using Greenshot.Configuration; @@ -30,14 +29,14 @@ using GreenshotPlugin.Core; using Greenshot.Plugin; using Greenshot.Helpers; using Greenshot.IniFile; -using Greenshot.Core; +using log4net; namespace Greenshot.Destinations { /// /// Description of PrinterDestination. /// public class PrinterDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PrinterDestination)); + private static ILog LOG = LogManager.GetLogger(typeof(PrinterDestination)); private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "Printer"; public string printerName = null; @@ -78,7 +77,7 @@ namespace Greenshot.Destinations { public override Image DisplayIcon { get { - return GreenshotPlugin.Core.GreenshotResources.getImage("Printer.Image"); + return GreenshotResources.getImage("Printer.Image"); } } @@ -106,7 +105,7 @@ namespace Greenshot.Destinations { /// /// ExportInformation public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); PrinterSettings printerSettings = null; if (!string.IsNullOrEmpty(printerName)) { using (PrintHelper printHelper = new PrintHelper(surface, captureDetails)) { diff --git a/Greenshot/Drawing/ArrowContainer.cs b/Greenshot/Drawing/ArrowContainer.cs index 9e35aa260..2708a2c9e 100644 --- a/Greenshot/Drawing/ArrowContainer.cs +++ b/Greenshot/Drawing/ArrowContainer.cs @@ -23,7 +23,6 @@ using System.Drawing; using System.Drawing.Drawing2D; using Greenshot.Drawing.Fields; -using Greenshot.Helpers; using Greenshot.Plugin.Drawing; namespace Greenshot.Drawing { @@ -41,7 +40,7 @@ namespace Greenshot.Drawing { AddField(GetType(), FieldType.LINE_COLOR, Color.Red); AddField(GetType(), FieldType.FILL_COLOR, Color.Transparent); AddField(GetType(), FieldType.SHADOW, true); - AddField(GetType(), FieldType.ARROWHEADS, Greenshot.Drawing.ArrowContainer.ArrowHeadCombination.END_POINT); + AddField(GetType(), FieldType.ARROWHEADS, ArrowHeadCombination.END_POINT); } public override void Draw(Graphics graphics, RenderMode rm) { @@ -67,10 +66,10 @@ namespace Greenshot.Drawing { SetArrowHeads(heads, shadowCapPen); graphics.DrawLine(shadowCapPen, - this.Left + currentStep, - this.Top + currentStep, - this.Left + currentStep + this.Width, - this.Top + currentStep + this.Height); + Left + currentStep, + Top + currentStep, + Left + currentStep + Width, + Top + currentStep + Height); currentStep++; alpha = alpha - (basealpha / steps); @@ -80,7 +79,7 @@ namespace Greenshot.Drawing { } using (Pen pen = new Pen(lineColor, lineThickness)) { SetArrowHeads(heads, pen); - graphics.DrawLine(pen, this.Left, this.Top, this.Left + this.Width, this.Top + this.Height); + graphics.DrawLine(pen, Left, Top, Left + Width, Top + Height); } } } @@ -103,7 +102,7 @@ namespace Greenshot.Drawing { pen.Width = lineThickness; SetArrowHeads((ArrowHeadCombination)GetFieldValue(FieldType.ARROWHEADS), pen); using (GraphicsPath path = new GraphicsPath()) { - path.AddLine(this.Left, this.Top, this.Left + this.Width, this.Top + this.Height); + path.AddLine(Left, Top, Left + Width, Top + Height); Rectangle drawingBounds = Rectangle.Round(path.GetBounds(new Matrix(), pen)); drawingBounds.Inflate(2, 2); return drawingBounds; @@ -122,7 +121,7 @@ namespace Greenshot.Drawing { pen.Width = lineThickness; SetArrowHeads((ArrowHeadCombination)GetFieldValue(FieldType.ARROWHEADS), pen); using (GraphicsPath path = new GraphicsPath()) { - path.AddLine(this.Left, this.Top, this.Left + this.Width, this.Top + this.Height); + path.AddLine(Left, Top, Left + Width, Top + Height); return path.IsOutlineVisible(x, y, pen); } } diff --git a/Greenshot/Drawing/CropContainer.cs b/Greenshot/Drawing/CropContainer.cs index 129bbc6ef..6a6aa20f4 100644 --- a/Greenshot/Drawing/CropContainer.cs +++ b/Greenshot/Drawing/CropContainer.cs @@ -18,10 +18,8 @@ * 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 System.Drawing; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; @@ -51,7 +49,7 @@ namespace Greenshot.Drawing { public override void Draw(Graphics g, RenderMode rm) { using (Brush cropBrush = new SolidBrush(Color.FromArgb(100, 150, 150, 100))) { - Rectangle cropRectangle = GuiRectangle.GetGuiRectangle(this.Left, this.Top, this.Width, this.Height); + Rectangle cropRectangle = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); Rectangle selectionRect = new Rectangle(cropRectangle.Left - 1, cropRectangle.Top - 1, cropRectangle.Width + 1, cropRectangle.Height + 1); DrawSelectionBorder(g, selectionRect); diff --git a/Greenshot/Drawing/CursorContainer.cs b/Greenshot/Drawing/CursorContainer.cs index afbe7f7be..5fca847be 100644 --- a/Greenshot/Drawing/CursorContainer.cs +++ b/Greenshot/Drawing/CursorContainer.cs @@ -25,6 +25,7 @@ using System.Windows.Forms; using Greenshot.Plugin.Drawing; using System.Drawing.Drawing2D; +using log4net; namespace Greenshot.Drawing { /// @@ -32,7 +33,7 @@ namespace Greenshot.Drawing { /// [Serializable()] public class CursorContainer : DrawableContainer, ICursorContainer { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(CursorContainer)); + private static ILog LOG = LogManager.GetLogger(typeof(CursorContainer)); protected Cursor cursor; diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index 70323ad4a..65d30914f 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -33,6 +33,7 @@ using Greenshot.Memento; using System.Drawing.Drawing2D; using Greenshot.Configuration; using Greenshot.IniFile; +using log4net; namespace Greenshot.Drawing { /// @@ -43,7 +44,7 @@ namespace Greenshot.Drawing { /// [Serializable()] public abstract class DrawableContainer : AbstractFieldHolderWithChildren, INotifyPropertyChanged, IDrawableContainer { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(DrawableContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer)); protected static readonly EditorConfiguration editorConfig = IniConfig.GetIniSection(); private bool isMadeUndoable = false; @@ -269,20 +270,20 @@ namespace Greenshot.Drawing { Left = lineThickness/2; } if (horizontalAlignment == HorizontalAlignment.Right) { - Left = parent.Width - this.Width - lineThickness/2; + Left = parent.Width - Width - lineThickness/2; } if (horizontalAlignment == HorizontalAlignment.Center) { - Left = (parent.Width / 2) - (this.Width / 2) - lineThickness/2; + Left = (parent.Width / 2) - (Width / 2) - lineThickness/2; } if (verticalAlignment == VerticalAlignment.TOP) { Top = lineThickness/2; } if (verticalAlignment == VerticalAlignment.BOTTOM) { - Top = parent.Height - this.Height - lineThickness/2; + Top = parent.Height - Height - lineThickness/2; } if (verticalAlignment == VerticalAlignment.CENTER) { - Top = (parent.Height / 2) - (this.Height / 2) - lineThickness/2; + Top = (parent.Height / 2) - (Height / 2) - lineThickness/2; } } @@ -301,9 +302,9 @@ namespace Greenshot.Drawing { for(int i=0; i @@ -516,14 +517,14 @@ namespace Greenshot.Drawing { /// /// true means allow the moves to be merged public void MakeBoundsChangeUndoable(bool allowMerge) { - this.parent.MakeUndoable(new DrawableContainerBoundsChangeMemento(this), allowMerge); + parent.MakeUndoable(new DrawableContainerBoundsChangeMemento(this), allowMerge); } public void MoveBy(int dx, int dy) { - this.SuspendLayout(); - this.Left += dx; - this.Top += dy; - this.ResumeLayout(); + SuspendLayout(); + Left += dx; + Top += dy; + ResumeLayout(); } /// diff --git a/Greenshot/Drawing/DrawableContainerList.cs b/Greenshot/Drawing/DrawableContainerList.cs index febf097af..421844cda 100644 --- a/Greenshot/Drawing/DrawableContainerList.cs +++ b/Greenshot/Drawing/DrawableContainerList.cs @@ -20,7 +20,9 @@ */ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Drawing; +using System.Threading; using Greenshot.Drawing.Fields; using Greenshot.Memento; using Greenshot.Plugin; @@ -29,7 +31,6 @@ using System.Windows.Forms; using GreenshotPlugin.Core; using Greenshot.IniFile; using Greenshot.Configuration; -using Greenshot.Helpers; namespace Greenshot.Drawing { /// @@ -38,7 +39,7 @@ namespace Greenshot.Drawing { [Serializable()] public class DrawableContainerList : List { private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static System.ComponentModel.ComponentResourceManager editorFormResources = new System.ComponentModel.ComponentResourceManager(typeof(ImageEditorForm)); + private static ComponentResourceManager editorFormResources = new ComponentResourceManager(typeof(ImageEditorForm)); public Guid ParentID { get; @@ -135,14 +136,14 @@ namespace Greenshot.Drawing { bool modified = false; // Invalidate before moving, otherwise the old locations aren't refreshed - this.Invalidate(); + Invalidate(); foreach(DrawableContainer dc in this) { dc.Left += dx; dc.Top += dy; modified = true; } // Invalidate after - this.Invalidate(); + Invalidate(); // If we moved something, tell the surface it's modified! if (modified) { @@ -275,11 +276,11 @@ namespace Greenshot.Drawing { /// list of elements to pull up /// true if the elements could be pulled up public bool CanPullUp(DrawableContainerList elements) { - if (elements.Count == 0 || elements.Count == this.Count) { + if (elements.Count == 0 || elements.Count == Count) { return false; } foreach(DrawableContainer element in elements) { - if (this.IndexOf(element) < this.Count - elements.Count) { + if (IndexOf(element) < Count - elements.Count) { return true; } } @@ -291,7 +292,7 @@ namespace Greenshot.Drawing { /// /// list of elements to pull up public void PullElementsUp(DrawableContainerList elements) { - for(int i=this.Count-1; i>=0; i--) { + for(int i=Count-1; i>=0; i--) { IDrawableContainer dc = this[i]; if (elements.Contains(dc)) { if (Count > (i+1) && !elements.Contains(this[i+1])) { @@ -306,12 +307,12 @@ namespace Greenshot.Drawing { /// /// of elements to pull to top public void PullElementsToTop(DrawableContainerList elements) { - IDrawableContainer[] dcs = this.ToArray(); + IDrawableContainer[] dcs = ToArray(); for(int i=0; ilist of elements to push down /// true if the elements could be pushed down public bool CanPushDown(DrawableContainerList elements) { - if (elements.Count == 0 || elements.Count == this.Count) { + if (elements.Count == 0 || elements.Count == Count) { return false; } foreach(DrawableContainer element in elements) { - if (this.IndexOf(element) >= elements.Count) { + if (IndexOf(element) >= elements.Count) { return true; } } @@ -355,12 +356,12 @@ namespace Greenshot.Drawing { /// /// of elements to push to bottom public void PushElementsToBottom(DrawableContainerList elements) { - IDrawableContainer[] dcs = this.ToArray(); + IDrawableContainer[] dcs = ToArray(); for(int i=dcs.Length-1; i>=0; i--) { IDrawableContainer dc = dcs[i]; if(elements.Contains(dc)) { - this.Remove(dc); - this.Insert(0, dc); + Remove(dc); + Insert(0, dc); Parent.Modified = true; } } @@ -436,7 +437,7 @@ namespace Greenshot.Drawing { // Copy item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)); - item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); + item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); }; @@ -444,7 +445,7 @@ namespace Greenshot.Drawing { // Cut item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)); - item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("btnCut.Image"))); + item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image"))); item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); List containersToDelete = new List(); @@ -459,7 +460,7 @@ namespace Greenshot.Drawing { // Delete item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement)); - item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); + item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); item.Click += delegate { List containersToDelete = new List(); foreach(DrawableContainer container in this) { @@ -513,7 +514,7 @@ namespace Greenshot.Drawing { while (true) { if (menu.Visible) { Application.DoEvents(); - System.Threading.Thread.Sleep(100); + Thread.Sleep(100); } else { menu.Dispose(); break; diff --git a/Greenshot/Drawing/EllipseContainer.cs b/Greenshot/Drawing/EllipseContainer.cs index 3acfad3f1..2c0eb8859 100644 --- a/Greenshot/Drawing/EllipseContainer.cs +++ b/Greenshot/Drawing/EllipseContainer.cs @@ -67,7 +67,7 @@ namespace Greenshot.Drawing { } } //draw the original shape - Rectangle rect = GuiRectangle.GetGuiRectangle(this.Left, this.Top, this.Width, this.Height); + Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); if (Colors.IsVisible(fillColor)) { using (Brush brush = new SolidBrush(fillColor)) { graphics.FillEllipse(brush, rect); @@ -88,7 +88,7 @@ namespace Greenshot.Drawing { } public override bool ClickableAt(int x, int y) { - Rectangle rect = GuiRectangle.GetGuiRectangle(this.Left, this.Top, this.Width, this.Height); + Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS) + 10; Color fillColor = GetFieldValueAsColor(FieldType.FILL_COLOR); diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs index f3bcee1ab..3beecac78 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs @@ -25,6 +25,7 @@ using System.Runtime.Serialization; using Greenshot.Configuration; using Greenshot.IniFile; +using log4net; namespace Greenshot.Drawing.Fields { /// @@ -32,7 +33,7 @@ namespace Greenshot.Drawing.Fields { /// [Serializable()] public abstract class AbstractFieldHolder : IFieldHolder { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(AbstractFieldHolder)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder)); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); /// @@ -53,7 +54,7 @@ namespace Greenshot.Drawing.Fields { public AbstractFieldHolder() {} - [OnDeserializedAttribute()] + [OnDeserialized()] private void OnDeserialized(StreamingContext context) { fieldsByType = new Dictionary(); // listen to changing properties diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs index fd55a6ab5..7eaf07a46 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -43,10 +43,10 @@ namespace Greenshot.Drawing.Fields { public List Children = new List(); public AbstractFieldHolderWithChildren() { - fieldChangedEventHandler = new FieldChangedEventHandler(OnFieldChanged); + fieldChangedEventHandler = OnFieldChanged; } - [OnDeserializedAttribute()] + [OnDeserialized()] private void OnDeserialized(StreamingContext context) { // listen to changing properties foreach(IFieldHolder fieldHolder in Children) { diff --git a/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs b/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs index d0ee5f83a..6ebbd4be1 100644 --- a/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs +++ b/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs @@ -56,8 +56,8 @@ namespace Greenshot.Drawing.Fields.Binding { this.controlPropertyName = controlPropertyName; this.fieldPropertyName = fieldPropertyName; - this.controlObject.PropertyChanged += new PropertyChangedEventHandler(ControlPropertyChanged); - this.fieldObject.PropertyChanged += new PropertyChangedEventHandler(FieldPropertyChanged); + this.controlObject.PropertyChanged += ControlPropertyChanged; + this.fieldObject.PropertyChanged += FieldPropertyChanged; } /// diff --git a/Greenshot/Drawing/Fields/Binding/IBindingConverter.cs b/Greenshot/Drawing/Fields/Binding/IBindingConverter.cs index 47873880a..a740da9d4 100644 --- a/Greenshot/Drawing/Fields/Binding/IBindingConverter.cs +++ b/Greenshot/Drawing/Fields/Binding/IBindingConverter.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 Greenshot.Drawing.Fields.Binding { diff --git a/Greenshot/Drawing/Fields/Binding/IBindingValidator.cs b/Greenshot/Drawing/Fields/Binding/IBindingValidator.cs index 118199097..aff1105d6 100644 --- a/Greenshot/Drawing/Fields/Binding/IBindingValidator.cs +++ b/Greenshot/Drawing/Fields/Binding/IBindingValidator.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 Greenshot.Drawing.Fields.Binding { diff --git a/Greenshot/Drawing/Fields/Binding/NotNullValidator.cs b/Greenshot/Drawing/Fields/Binding/NotNullValidator.cs index bfebe3875..50718539a 100644 --- a/Greenshot/Drawing/Fields/Binding/NotNullValidator.cs +++ b/Greenshot/Drawing/Fields/Binding/NotNullValidator.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 Greenshot.Drawing.Fields.Binding { /// diff --git a/Greenshot/Drawing/Fields/Field.cs b/Greenshot/Drawing/Fields/Field.cs index 308eef0e4..a2b572075 100644 --- a/Greenshot/Drawing/Fields/Field.cs +++ b/Greenshot/Drawing/Fields/Field.cs @@ -37,7 +37,7 @@ namespace Greenshot.Drawing.Fields { return myValue; } set { - if (!object.Equals(myValue,value)) { + if (!Equals(myValue,value)) { myValue = value; if (PropertyChanged!=null) { PropertyChanged(this, new PropertyChangedEventArgs("Value")); @@ -102,11 +102,11 @@ namespace Greenshot.Drawing.Fields { if (other == null) { return false; } - return this.FieldType == other.FieldType && object.Equals(this.Scope, other.Scope); + return FieldType == other.FieldType && Equals(Scope, other.Scope); } public override string ToString() { - return string.Format("[Field FieldType={1} Value={0} Scope={2}]", this.myValue, this.FieldType, this.Scope); + return string.Format("[Field FieldType={1} Value={0} Scope={2}]", myValue, FieldType, Scope); } } @@ -122,7 +122,7 @@ namespace Greenshot.Drawing.Fields { public class FieldChangedEventArgs : EventArgs { public readonly Field Field; public FieldChangedEventArgs(Field field) { - this.Field = field; + Field = field; } } } diff --git a/Greenshot/Drawing/Fields/FieldAggregator.cs b/Greenshot/Drawing/Fields/FieldAggregator.cs index f0d5966ae..b117e0b4d 100644 --- a/Greenshot/Drawing/Fields/FieldAggregator.cs +++ b/Greenshot/Drawing/Fields/FieldAggregator.cs @@ -18,13 +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.Collections.Generic; using System.ComponentModel; using Greenshot.Configuration; using Greenshot.IniFile; using Greenshot.Plugin.Drawing; +using log4net; namespace Greenshot.Drawing.Fields { /// @@ -45,7 +46,7 @@ namespace Greenshot.Drawing.Fields { enum Status {IDLE, BINDING, UPDATING}; - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(FieldAggregator)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator)); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); public FieldAggregator() { @@ -58,7 +59,7 @@ namespace Greenshot.Drawing.Fields { public override void AddField(Field field) { base.AddField(field); - field.PropertyChanged += new PropertyChangedEventHandler(OwnPropertyChanged); + field.PropertyChanged += OwnPropertyChanged; } public void BindElements(DrawableContainerList dcs) { diff --git a/Greenshot/Drawing/Fields/FieldType.cs b/Greenshot/Drawing/Fields/FieldType.cs index b7a536b4c..82fd5631e 100644 --- a/Greenshot/Drawing/Fields/FieldType.cs +++ b/Greenshot/Drawing/Fields/FieldType.cs @@ -84,7 +84,7 @@ namespace Greenshot.Drawing.Fields { Name = name; } public override string ToString() { - return this.Name; + return Name; } public override int GetHashCode() { @@ -101,15 +101,15 @@ namespace Greenshot.Drawing.Fields { FieldType other = obj as FieldType; if (other == null) return false; - return object.Equals(this.Name,other.Name); + return Equals(Name,other.Name); } public static bool operator ==(FieldType a, FieldType b) { - return object.Equals(a,b); + return Equals(a,b); } public static bool operator !=(FieldType a, FieldType b) { - return !object.Equals(a,b); + return !Equals(a,b); } } diff --git a/Greenshot/Drawing/Fields/IFieldHolder.cs b/Greenshot/Drawing/Fields/IFieldHolder.cs index 49e832b7d..f6c0d0ad0 100644 --- a/Greenshot/Drawing/Fields/IFieldHolder.cs +++ b/Greenshot/Drawing/Fields/IFieldHolder.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; namespace Greenshot.Drawing.Fields { diff --git a/Greenshot/Drawing/FilterContainer.cs b/Greenshot/Drawing/FilterContainer.cs index 9aaa9ea83..583589a19 100644 --- a/Greenshot/Drawing/FilterContainer.cs +++ b/Greenshot/Drawing/FilterContainer.cs @@ -63,14 +63,14 @@ namespace Greenshot.Drawing { int currentStep = lineVisible ? 1 : 0; while (currentStep <= steps) { using (Pen shadowPen = new Pen(Color.FromArgb(alpha, 100, 100, 100), lineThickness)) { - Rectangle shadowRect = GuiRectangle.GetGuiRectangle(this.Left + currentStep, this.Top + currentStep, this.Width, this.Height); + Rectangle shadowRect = GuiRectangle.GetGuiRectangle(Left + currentStep, Top + currentStep, Width, Height); graphics.DrawRectangle(shadowPen, shadowRect); currentStep++; alpha = alpha - (basealpha / steps); } } } - Rectangle rect = GuiRectangle.GetGuiRectangle(this.Left, this.Top, this.Width, this.Height); + Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); if (lineThickness > 0) { using (Pen pen = new Pen(lineColor, lineThickness)) { graphics.DrawRectangle(pen, rect); diff --git a/Greenshot/Drawing/Filters/AbstractFilter.cs b/Greenshot/Drawing/Filters/AbstractFilter.cs index cdb1a5882..7fae8888c 100644 --- a/Greenshot/Drawing/Filters/AbstractFilter.cs +++ b/Greenshot/Drawing/Filters/AbstractFilter.cs @@ -24,7 +24,6 @@ using System.Drawing; using Greenshot.Drawing.Fields; using Greenshot.Plugin.Drawing; -using GreenshotPlugin.Core; /// /// Graphical filter which can be added to DrawableContainer. diff --git a/Greenshot/Drawing/Filters/BlurFilter.cs b/Greenshot/Drawing/Filters/BlurFilter.cs index 728345063..63f62b2bb 100644 --- a/Greenshot/Drawing/Filters/BlurFilter.cs +++ b/Greenshot/Drawing/Filters/BlurFilter.cs @@ -23,14 +23,14 @@ using System.Drawing; using Greenshot.Drawing.Fields; using Greenshot.Plugin.Drawing; using GreenshotPlugin.Core; -using System.Drawing.Imaging; using GreenshotPlugin.UnmanagedHelpers; using System.Drawing.Drawing2D; +using log4net; namespace Greenshot.Drawing.Filters { [Serializable()] public class BlurFilter : AbstractFilter { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(BlurFilter)); + private static ILog LOG = LogManager.GetLogger(typeof(BlurFilter)); public double previewQuality; public double PreviewQuality { diff --git a/Greenshot/Drawing/Filters/GrayscaleFilter.cs b/Greenshot/Drawing/Filters/GrayscaleFilter.cs index 5ad8101fe..3478977fe 100644 --- a/Greenshot/Drawing/Filters/GrayscaleFilter.cs +++ b/Greenshot/Drawing/Filters/GrayscaleFilter.cs @@ -46,10 +46,10 @@ namespace Greenshot.Drawing.Filters { graphics.SetClip(applyRect); graphics.ExcludeClip(rect); } - 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/Greenshot/Drawing/Filters/HighlightFilter.cs b/Greenshot/Drawing/Filters/HighlightFilter.cs index 3991a5ee1..4b25335c0 100644 --- a/Greenshot/Drawing/Filters/HighlightFilter.cs +++ b/Greenshot/Drawing/Filters/HighlightFilter.cs @@ -23,7 +23,6 @@ using System.Drawing; using Greenshot.Drawing.Fields; using Greenshot.Plugin.Drawing; using GreenshotPlugin.Core; -using System.Drawing.Imaging; using System.Drawing.Drawing2D; namespace Greenshot.Drawing.Filters { diff --git a/Greenshot/Drawing/Filters/IFilter.cs b/Greenshot/Drawing/Filters/IFilter.cs index dc7109168..3edbe4690 100644 --- a/Greenshot/Drawing/Filters/IFilter.cs +++ b/Greenshot/Drawing/Filters/IFilter.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.Drawing; diff --git a/Greenshot/Drawing/Filters/MagnifierFilter.cs b/Greenshot/Drawing/Filters/MagnifierFilter.cs index 9e32a4813..c0e0c93c8 100644 --- a/Greenshot/Drawing/Filters/MagnifierFilter.cs +++ b/Greenshot/Drawing/Filters/MagnifierFilter.cs @@ -23,7 +23,6 @@ using System.Drawing; using Greenshot.Drawing.Fields; using Greenshot.Plugin.Drawing; using GreenshotPlugin.Core; -using System.Drawing.Imaging; using System.Drawing.Drawing2D; namespace Greenshot.Drawing.Filters { diff --git a/Greenshot/Drawing/FreehandContainer.cs b/Greenshot/Drawing/FreehandContainer.cs index 9068a9286..de955f3ef 100644 --- a/Greenshot/Drawing/FreehandContainer.cs +++ b/Greenshot/Drawing/FreehandContainer.cs @@ -21,12 +21,12 @@ using System; using System.Drawing; using System.Drawing.Drawing2D; -using System.ComponentModel; using System.Collections.Generic; using System.Runtime.Serialization; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; +using log4net; namespace Greenshot.Drawing { /// @@ -34,7 +34,7 @@ namespace Greenshot.Drawing { /// [Serializable()] public class FreehandContainer : DrawableContainer { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(FreehandContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(FreehandContainer)); private static readonly float [] POINT_OFFSET = new float[]{0.5f, 0.25f, 0.75f}; [NonSerialized] @@ -66,7 +66,7 @@ namespace Greenshot.Drawing { } } - [OnDeserializedAttribute()] + [OnDeserialized()] private void OnDeserialized(StreamingContext context) { InitGrippers(); DoLayout(); @@ -258,7 +258,7 @@ namespace Greenshot.Drawing { } public override void ShowGrippers() { - this.ResumeLayout(); + ResumeLayout(); } public override bool ClickableAt(int x, int y) { diff --git a/Greenshot/Drawing/Gripper.cs b/Greenshot/Drawing/Gripper.cs index 70b2888fc..99f4c1bcb 100644 --- a/Greenshot/Drawing/Gripper.cs +++ b/Greenshot/Drawing/Gripper.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.Drawing; using System.Windows.Forms; diff --git a/Greenshot/Drawing/HighlightContainer.cs b/Greenshot/Drawing/HighlightContainer.cs index 668dc45c1..188134040 100644 --- a/Greenshot/Drawing/HighlightContainer.cs +++ b/Greenshot/Drawing/HighlightContainer.cs @@ -35,11 +35,11 @@ namespace Greenshot.Drawing { AddField(GetType(), FieldType.LINE_THICKNESS, 0); AddField(GetType(), FieldType.LINE_COLOR, Color.Red); AddField(GetType(), FieldType.SHADOW, false); - AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, FilterContainer.PreparedFilter.TEXT_HIGHTLIGHT); + AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT); init(); } - [OnDeserializedAttribute()] + [OnDeserialized()] private void OnDeserialized(StreamingContext context) { init(); } diff --git a/Greenshot/Drawing/IconContainer.cs b/Greenshot/Drawing/IconContainer.cs index 0eb2b0a36..54d36fd82 100644 --- a/Greenshot/Drawing/IconContainer.cs +++ b/Greenshot/Drawing/IconContainer.cs @@ -21,10 +21,9 @@ using System; using System.Drawing; using System.IO; -using System.Windows.Forms; - using Greenshot.Plugin.Drawing; using System.Drawing.Drawing2D; +using log4net; namespace Greenshot.Drawing { /// @@ -32,7 +31,7 @@ namespace Greenshot.Drawing { /// [Serializable()] public class IconContainer : DrawableContainer, IIconContainer { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IconContainer)); + private static ILog LOG = LogManager.GetLogger(typeof(IconContainer)); protected Icon icon; diff --git a/Greenshot/Drawing/ImageContainer.cs b/Greenshot/Drawing/ImageContainer.cs index 57c77c035..1c1a5e3b5 100644 --- a/Greenshot/Drawing/ImageContainer.cs +++ b/Greenshot/Drawing/ImageContainer.cs @@ -20,16 +20,13 @@ */ using System; using System.Drawing; -using System.Drawing.Imaging; using System.IO; -using System.Windows.Forms; - using Greenshot.Drawing.Fields; -using Greenshot.Helpers; using Greenshot.Plugin.Drawing; using GreenshotPlugin.Core; using System.Drawing.Drawing2D; using Greenshot.Core; +using log4net; namespace Greenshot.Drawing { /// @@ -37,7 +34,7 @@ namespace Greenshot.Drawing { /// [Serializable()] public class ImageContainer : DrawableContainer, IImageContainer { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImageContainer)); + private static ILog LOG = LogManager.GetLogger(typeof(ImageContainer)); private Image image; @@ -76,16 +73,16 @@ namespace Greenshot.Drawing { bool shadow = GetFieldValueAsBool(FieldType.SHADOW); if (shadow) { CheckShadow(shadow); - this.Width = shadowBitmap.Width; - this.Height = shadowBitmap.Height; - this.Left = this.Left - this.shadowOffset.X; - this.Top = this.Top - this.shadowOffset.Y; + Width = shadowBitmap.Width; + Height = shadowBitmap.Height; + Left = Left - shadowOffset.X; + Top = Top - shadowOffset.Y; } else { - this.Width = image.Width; - this.Height = image.Height; + Width = image.Width; + Height = image.Height; if (shadowBitmap != null) { - this.Left = this.Left + this.shadowOffset.X; - this.Top = this.Top + this.shadowOffset.Y; + Left = Left + shadowOffset.X; + Top = Top + shadowOffset.Y; } } } @@ -103,8 +100,8 @@ namespace Greenshot.Drawing { } else { Width = shadowBitmap.Width; Height = shadowBitmap.Height; - this.Left = this.Left - this.shadowOffset.X; - this.Top = this.Top - this.shadowOffset.Y; + Left = Left - shadowOffset.X; + Top = Top - shadowOffset.Y; } } get { return image; } diff --git a/Greenshot/Drawing/LineContainer.cs b/Greenshot/Drawing/LineContainer.cs index a1bb6d884..be8ea477f 100644 --- a/Greenshot/Drawing/LineContainer.cs +++ b/Greenshot/Drawing/LineContainer.cs @@ -42,7 +42,7 @@ namespace Greenshot.Drawing { AddField(GetType(), FieldType.SHADOW, true); } - [OnDeserializedAttribute()] + [OnDeserialized()] private void OnDeserialized(StreamingContext context) { InitGrippers(); DoLayout(); @@ -51,7 +51,7 @@ namespace Greenshot.Drawing { protected void Init() { if (grippers != null) { - foreach (int index in new int[] { 1, 2, 3, 5, 6, 7 }) { + foreach (int index in new[] { 1, 2, 3, 5, 6, 7 }) { grippers[index].Enabled = false; } } @@ -77,10 +77,10 @@ namespace Greenshot.Drawing { while (currentStep <= steps) { using (Pen shadowCapPen = new Pen(Color.FromArgb(alpha, 100, 100, 100), lineThickness)) { graphics.DrawLine(shadowCapPen, - this.Left + currentStep, - this.Top + currentStep, - this.Left + currentStep + this.Width, - this.Top + currentStep + this.Height); + Left + currentStep, + Top + currentStep, + Left + currentStep + Width, + Top + currentStep + Height); currentStep++; alpha = alpha - (basealpha / steps); @@ -89,7 +89,7 @@ namespace Greenshot.Drawing { } using (Pen pen = new Pen(lineColor, lineThickness)) { - graphics.DrawLine(pen, this.Left, this.Top, this.Left + this.Width, this.Top + this.Height); + graphics.DrawLine(pen, Left, Top, Left + Width, Top + Height); } } } @@ -100,7 +100,7 @@ namespace Greenshot.Drawing { using (Pen pen = new Pen(Color.White)) { pen.Width = lineThickness; using (GraphicsPath path = new GraphicsPath()) { - path.AddLine(this.Left, this.Top, this.Left + this.Width, this.Top + this.Height); + path.AddLine(Left, Top, Left + Width, Top + Height); return path.IsOutlineVisible(x, y, pen); } } diff --git a/Greenshot/Drawing/ObfuscateContainer.cs b/Greenshot/Drawing/ObfuscateContainer.cs index 0142b0de2..c7b189984 100644 --- a/Greenshot/Drawing/ObfuscateContainer.cs +++ b/Greenshot/Drawing/ObfuscateContainer.cs @@ -30,11 +30,11 @@ namespace Greenshot.Drawing { [Serializable()] public class ObfuscateContainer : FilterContainer { public ObfuscateContainer(Surface parent) : base(parent) { - AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, FilterContainer.PreparedFilter.PIXELIZE); + AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE); init(); } - [OnDeserializedAttribute()] + [OnDeserialized()] private void OnDeserialized(StreamingContext context) { init(); } diff --git a/Greenshot/Drawing/RectangleContainer.cs b/Greenshot/Drawing/RectangleContainer.cs index 56a7d3a7c..0a20ed6ab 100644 --- a/Greenshot/Drawing/RectangleContainer.cs +++ b/Greenshot/Drawing/RectangleContainer.cs @@ -24,6 +24,7 @@ using System.Drawing.Drawing2D; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; +using log4net; namespace Greenshot.Drawing { /// @@ -31,7 +32,7 @@ namespace Greenshot.Drawing { /// [Serializable()] public class RectangleContainer : DrawableContainer { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(RectangleContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(RectangleContainer)); public RectangleContainer(Surface parent) : base(parent) { AddField(GetType(), FieldType.LINE_THICKNESS, 2); @@ -62,10 +63,10 @@ namespace Greenshot.Drawing { using (Pen shadowPen = new Pen(Color.FromArgb(alpha, 100, 100, 100))) { shadowPen.Width = lineVisible ? lineThickness : 1; Rectangle shadowRect = GuiRectangle.GetGuiRectangle( - this.Left + currentStep, - this.Top + currentStep, - this.Width, - this.Height); + Left + currentStep, + Top + currentStep, + Width, + Height); graphics.DrawRectangle(shadowPen, shadowRect); currentStep++; alpha = alpha - (basealpha / steps); @@ -73,7 +74,7 @@ namespace Greenshot.Drawing { } } - Rectangle rect = GuiRectangle.GetGuiRectangle(this.Left, this.Top, this.Width, this.Height); + Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); if (Colors.IsVisible(fillColor)) { using (Brush brush = new SolidBrush(fillColor)) { @@ -90,7 +91,7 @@ namespace Greenshot.Drawing { } public override bool ClickableAt(int x, int y) { - Rectangle rect = GuiRectangle.GetGuiRectangle(this.Left, this.Top, this.Width, this.Height); + Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS) + 10; Color fillColor = GetFieldValueAsColor(FieldType.FILL_COLOR); diff --git a/Greenshot/Drawing/RoundedRectangle.cs b/Greenshot/Drawing/RoundedRectangle.cs index 306e913dc..56f93f240 100644 --- a/Greenshot/Drawing/RoundedRectangle.cs +++ b/Greenshot/Drawing/RoundedRectangle.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.Drawing; using System.Drawing.Drawing2D; diff --git a/Greenshot/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index 0e1438a98..a1bf70d51 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -34,10 +34,9 @@ using Greenshot.Plugin.Drawing; using GreenshotPlugin.Core; using Greenshot.Memento; using Greenshot.IniFile; -using Greenshot.Drawing.Filters; -using System.Drawing.Drawing2D; using GreenshotPlugin.Controls; using Greenshot.Core; +using log4net; namespace Greenshot.Drawing { @@ -45,7 +44,7 @@ namespace Greenshot.Drawing { /// Description of Surface. /// public class Surface : Control, ISurface { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(Surface)); + private static ILog LOG = LogManager.GetLogger(typeof(Surface)); public static int Count = 0; private static CoreConfiguration conf = IniConfig.GetIniSection(); @@ -384,23 +383,23 @@ namespace Greenshot.Drawing { elements = new DrawableContainerList(uniqueID); selectedElements = new DrawableContainerList(uniqueID); LOG.Debug("Creating surface!"); - this.MouseDown += new MouseEventHandler(SurfaceMouseDown); - this.MouseUp += new MouseEventHandler(SurfaceMouseUp); - this.MouseMove += new MouseEventHandler(SurfaceMouseMove); - this.MouseDoubleClick += new MouseEventHandler(SurfaceDoubleClick); - this.Paint += new PaintEventHandler(SurfacePaint); - this.AllowDrop = true; - this.DragDrop += new DragEventHandler(OnDragDrop); - this.DragEnter += new DragEventHandler(OnDragEnter); + MouseDown += SurfaceMouseDown; + MouseUp += SurfaceMouseUp; + MouseMove += SurfaceMouseMove; + MouseDoubleClick += SurfaceDoubleClick; + Paint += SurfacePaint; + AllowDrop = true; + DragDrop += OnDragDrop; + DragEnter += OnDragEnter; // bind selected & elements to this, otherwise they can't inform of modifications - this.selectedElements.Parent = this; - this.elements.Parent = this; + selectedElements.Parent = this; + elements.Parent = this; // Make sure we are visible - this.Visible = true; - this.TabStop = false; + Visible = true; + TabStop = false; // Enable double buffering - this.DoubleBuffered = true; - this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.ContainerControl | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true); + DoubleBuffered = true; + SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.ContainerControl | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true); } /// @@ -767,7 +766,7 @@ namespace Greenshot.Drawing { /// private void OnDragDrop(object sender, DragEventArgs e) { List filenames = ClipboardHelper.GetImageFilenames(e.Data); - Point mouse = this.PointToClient(new Point(e.X, e.Y)); + Point mouse = PointToClient(new Point(e.X, e.Y)); if (e.Data.GetDataPresent("Text")) { string possibleUrl = ClipboardHelper.GetText(e.Data); // Test if it's an url and try to download the image so we have it in the original form @@ -875,7 +874,7 @@ namespace Greenshot.Drawing { /// /// true if this is possible public bool isCropPossible(ref Rectangle cropRectangle) { - cropRectangle = Helpers.GuiRectangle.GetGuiRectangle(cropRectangle.Left, cropRectangle.Top, cropRectangle.Width, cropRectangle.Height); + cropRectangle = GuiRectangle.GetGuiRectangle(cropRectangle.Left, cropRectangle.Top, cropRectangle.Width, cropRectangle.Height); if (cropRectangle.Left < 0) { cropRectangle = new Rectangle(0, cropRectangle.Top, cropRectangle.Width + cropRectangle.Left, cropRectangle.Height); } @@ -1046,7 +1045,7 @@ namespace Greenshot.Drawing { if (DrawingMode == DrawingModes.None) { // check whether an existing element was clicked IDrawableContainer element = elements.ClickableElementAt(currentMouse.X, currentMouse.Y); - bool shiftModifier = (Control.ModifierKeys & Keys.Shift) == Keys.Shift; + bool shiftModifier = (ModifierKeys & Keys.Shift) == Keys.Shift; if (element != null) { element.Invalidate(); bool alreadySelected = selectedElements.Contains(element); @@ -1228,7 +1227,7 @@ namespace Greenshot.Drawing { targetGraphics.FillRectangle(transparencyBackgroundBrush, clipRectangle); } else { Graphics targetGraphics = e.Graphics; - targetGraphics.Clear(this.BackColor); + targetGraphics.Clear(BackColor); //base.OnPaintBackground(e); } } @@ -1392,7 +1391,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 == this.uniqueID); + bool isSameSurface = (dcs.ParentID == uniqueID); dcs.Parent = this; if (isSameSurface) { moveOffset = new Point(10, 10); @@ -1575,7 +1574,7 @@ namespace Greenshot.Drawing { /// false if no keys were processed public bool ProcessCmdKey(Keys k) { if (selectedElements.Count > 0) { - bool shiftModifier = (Control.ModifierKeys & Keys.Shift) == Keys.Shift; + bool shiftModifier = (ModifierKeys & Keys.Shift) == Keys.Shift; int px = shiftModifier ? 10 : 1; Point moveBy = Point.Empty; diff --git a/Greenshot/Drawing/TextContainer.cs b/Greenshot/Drawing/TextContainer.cs index 460a3cb58..af9dd36fb 100644 --- a/Greenshot/Drawing/TextContainer.cs +++ b/Greenshot/Drawing/TextContainer.cs @@ -88,7 +88,7 @@ namespace Greenshot.Drawing { stringFormat.Trimming = StringTrimming.EllipsisWord; } - [OnDeserializedAttribute] + [OnDeserialized] private void OnDeserialized(StreamingContext context) { stringFormat = new StringFormat(); Init(); @@ -115,8 +115,8 @@ namespace Greenshot.Drawing { private void Init() { CreateTextBox(); - this.PropertyChanged += new PropertyChangedEventHandler(TextContainer_PropertyChanged); - this.FieldChanged += new FieldChangedEventHandler(TextContainer_FieldChanged); + PropertyChanged += TextContainer_PropertyChanged; + FieldChanged += TextContainer_FieldChanged; } public void FitToText() { @@ -168,8 +168,8 @@ namespace Greenshot.Drawing { textBox.AcceptsTab = true; textBox.AcceptsReturn = true; textBox.DataBindings.Add("Text", this, "Text", false, DataSourceUpdateMode.OnPropertyChanged); - textBox.LostFocus += new EventHandler(textBox_LostFocus); - textBox.KeyDown += new KeyEventHandler(textBox_KeyDown); + textBox.LostFocus += textBox_LostFocus; + textBox.KeyDown += textBox_KeyDown; textBox.BorderStyle = BorderStyle.FixedSingle; textBox.Visible = false; } @@ -186,7 +186,7 @@ namespace Greenshot.Drawing { /// Makes textbox background dark if text color is very bright /// private void EnsureTextBoxContrast() { - Color lc = this.GetFieldValueAsColor(FieldType.LINE_COLOR); + Color lc = GetFieldValueAsColor(FieldType.LINE_COLOR); if (lc.R > 203 && lc.G > 203 && lc.B > 203) { textBox.BackColor = Color.FromArgb(51, 51, 51); } else { @@ -253,10 +253,10 @@ namespace Greenshot.Drawing { } private void UpdateTextBoxPosition() { - textBox.Left = this.Left; - textBox.Top = this.Top; - textBox.Width = this.Width; - textBox.Height = this.Height; + textBox.Left = Left; + textBox.Top = Top; + textBox.Width = Width; + textBox.Height = Height; } public override void ApplyBounds(RectangleF newBounds) { @@ -294,7 +294,7 @@ namespace Greenshot.Drawing { graphics.PixelOffsetMode = PixelOffsetMode.None; graphics.TextRenderingHint = TextRenderingHint.SystemDefault; - Rectangle rect = GuiRectangle.GetGuiRectangle(this.Left, this.Top, this.Width, this.Height); + Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); if (Selected && rm == RenderMode.EDIT) { DrawSelectionBorder(graphics, rect); } diff --git a/Greenshot/Forms/AboutForm.Designer.cs b/Greenshot/Forms/AboutForm.Designer.cs index c2d46e01e..a9f204d9f 100644 --- a/Greenshot/Forms/AboutForm.Designer.cs +++ b/Greenshot/Forms/AboutForm.Designer.cs @@ -18,9 +18,6 @@ * 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 Greenshot { partial class AboutForm { diff --git a/Greenshot/Forms/AboutForm.cs b/Greenshot/Forms/AboutForm.cs index 0887ff6b5..caded2080 100644 --- a/Greenshot/Forms/AboutForm.cs +++ b/Greenshot/Forms/AboutForm.cs @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics; using System.Reflection; using System.Windows.Forms; using System.IO; @@ -32,15 +33,15 @@ using Greenshot.Helpers; using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.IniFile; -using GreenshotPlugin.Controls; using System.Security.Permissions; +using log4net; namespace Greenshot { /// /// The about form /// public partial class AboutForm : AnimatingBaseForm { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(AboutForm)); + private static ILog LOG = LogManager.GetLogger(typeof(AboutForm)); private Bitmap gBitmap; private ColorAnimator backgroundAnimation; private List pixels = new List(); @@ -132,10 +133,10 @@ namespace Greenshot { /// public AboutForm() { // Make sure our resources are removed again. - this.Disposed += delegate { + Disposed += delegate { Cleanup(); }; - this.FormClosing += delegate { + FormClosing += delegate { Cleanup(); }; @@ -150,11 +151,11 @@ namespace Greenshot { DoubleBuffered = !isTerminalServerSession; // Not needed for a Tool Window, but still for the task manager it's important - this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); + Icon = GreenshotResources.getGreenshotIcon(); // 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, this.BackColor, 96, 96); - this.pictureBox1.Image = gBitmap; + gBitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96); + pictureBox1.Image = gBitmap; Version v = Assembly.GetExecutingAssembly().GetName().Version; // Format is like this: AssemblyVersion("Major.Minor.Build.Revision")] @@ -209,7 +210,7 @@ namespace Greenshot { } while (pixelColorAnimator.hasNext); // color animation for the background - backgroundAnimation = new ColorAnimator(this.BackColor, backColor, FramesForMillis(5000), EasingType.Linear, EasingMode.EaseIn); + backgroundAnimation = new ColorAnimator(BackColor, backColor, FramesForMillis(5000), EasingType.Linear, EasingMode.EaseIn); } /// @@ -217,12 +218,12 @@ namespace Greenshot { /// /// /// - void LinkLabelClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { + void LinkLabelClicked(object sender, LinkLabelLinkClickedEventArgs e) { LinkLabel linkLabel = sender as LinkLabel; if (linkLabel != null) { try { linkLabel.LinkVisited = true; - System.Diagnostics.Process.Start(linkLabel.Text); + Process.Start(linkLabel.Text); } catch (Exception) { MessageBox.Show(Language.GetFormattedString(LangKey.error_openlink, linkLabel.Text), Language.GetString(LangKey.error)); } @@ -316,7 +317,7 @@ namespace Greenshot { case Keys.L: try { if (File.Exists(MainForm.LogFileLocation)) { - System.Diagnostics.Process.Start("\"" + MainForm.LogFileLocation + "\""); + Process.Start("\"" + MainForm.LogFileLocation + "\""); } else { MessageBox.Show("Greenshot can't find the logfile, it should have been here: " + MainForm.LogFileLocation); } @@ -326,9 +327,9 @@ namespace Greenshot { break; case Keys.I: try { - System.Diagnostics.Process.Start("\"" + IniFile.IniConfig.ConfigLocation + "\""); + Process.Start("\"" + IniConfig.ConfigLocation + "\""); } catch (Exception) { - MessageBox.Show("Couldn't open the greenshot.ini, it's located here: " + IniFile.IniConfig.ConfigLocation, "Error opening greeenshot.ini", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); + MessageBox.Show("Couldn't open the greenshot.ini, it's located here: " + IniConfig.ConfigLocation, "Error opening greeenshot.ini", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } break; default: diff --git a/Greenshot/Forms/AnimatingBaseForm.cs b/Greenshot/Forms/AnimatingBaseForm.cs index b2ee3b724..a2c13eea0 100644 --- a/Greenshot/Forms/AnimatingBaseForm.cs +++ b/Greenshot/Forms/AnimatingBaseForm.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 GreenshotPlugin.Controls; namespace Greenshot { diff --git a/Greenshot/Forms/BaseForm.cs b/Greenshot/Forms/BaseForm.cs index bd3239b80..f795ede8e 100644 --- a/Greenshot/Forms/BaseForm.cs +++ b/Greenshot/Forms/BaseForm.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 GreenshotPlugin.Controls; namespace Greenshot { diff --git a/Greenshot/Forms/BugReportForm.cs b/Greenshot/Forms/BugReportForm.cs index e730cee6a..31d2cd697 100644 --- a/Greenshot/Forms/BugReportForm.cs +++ b/Greenshot/Forms/BugReportForm.cs @@ -19,9 +19,9 @@ * along with this program. If not, see . */ using System; +using System.Diagnostics; using System.Windows.Forms; using Greenshot.Configuration; -using Greenshot.Helpers; using GreenshotPlugin.Core; namespace Greenshot.Forms { @@ -31,22 +31,22 @@ namespace Greenshot.Forms { // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); - this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); - WindowDetails.ToForeground(this.Handle); + Icon = GreenshotResources.getGreenshotIcon(); + WindowDetails.ToForeground(Handle); } public BugReportForm(string bugText) : this() { - this.textBoxDescription.Text = bugText; + textBoxDescription.Text = bugText; } - void LinkLblBugsLinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { + void LinkLblBugsLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { openLink((LinkLabel)sender); } private void openLink(LinkLabel link) { try { link.LinkVisited = true; - System.Diagnostics.Process.Start(link.Text); + Process.Start(link.Text); } catch (Exception) { MessageBox.Show(Language.GetFormattedString(LangKey.error_openlink, link.Text), Language.GetString(LangKey.error)); } diff --git a/Greenshot/Forms/CaptureForm.cs b/Greenshot/Forms/CaptureForm.cs index cf36345fc..41a784cb1 100644 --- a/Greenshot/Forms/CaptureForm.cs +++ b/Greenshot/Forms/CaptureForm.cs @@ -18,24 +18,22 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + +using System.Globalization; +using Greenshot.Drawing; +using Greenshot.Helpers; +using Greenshot.IniFile; +using Greenshot.Plugin; +using GreenshotPlugin.Controls; +using GreenshotPlugin.Core; +using log4net; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; -using System.Drawing.Printing; -using System.IO; -using System.Windows.Forms; -using Greenshot.Configuration; -using Greenshot.Drawing; -using Greenshot.Helpers; -using Greenshot.Plugin; -using GreenshotPlugin.UnmanagedHelpers; -using GreenshotPlugin.Core; -using Greenshot.IniFile; -using GreenshotPlugin.Controls; using System.Security.Permissions; +using System.Windows.Forms; namespace Greenshot.Forms { /// @@ -44,44 +42,43 @@ namespace Greenshot.Forms { public partial class CaptureForm : AnimatingForm { private enum FixMode {None, Initiated, Horizontal, Vertical}; - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(CaptureForm)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static Brush GreenOverlayBrush = new SolidBrush(Color.FromArgb(50, Color.MediumSeaGreen)); - private static Brush RedOverlayBrush = new SolidBrush(Color.FromArgb(50, Color.DarkRed)); - private static Pen OverlayPen = new Pen(Color.FromArgb(50, Color.Black)); - private static CaptureForm currentForm = null; - private static Brush backgroundBrush = null; + private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureForm)); + private static readonly CoreConfiguration Conf = IniConfig.GetIniSection(); + private static readonly Brush GreenOverlayBrush = new SolidBrush(Color.FromArgb(50, Color.MediumSeaGreen)); + private static readonly Pen OverlayPen = new Pen(Color.FromArgb(50, Color.Black)); + private static CaptureForm _currentForm; + private static readonly Brush BackgroundBrush; /// /// Initialize the background brush /// static CaptureForm() { - Image backgroundForTransparency = GreenshotPlugin.Core.GreenshotResources.getImage("Checkerboard.Image"); - backgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile); + Image backgroundForTransparency = GreenshotResources.getImage("Checkerboard.Image"); + BackgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile); } - private int mX; - private int mY; - private Point mouseMovePos = Point.Empty; - private Point cursorPos = Point.Empty; - private CaptureMode captureMode = CaptureMode.None; - private List windows = new List(); - private WindowDetails selectedCaptureWindow; - private bool mouseDown = false; - private Rectangle captureRect = Rectangle.Empty; - private ICapture capture = null; - private Image capturedImage = null; - private Point previousMousePos = Point.Empty; - private FixMode fixMode = FixMode.None; - private RectangleAnimator windowAnimator = null; - private RectangleAnimator zoomAnimator = null; - private bool isZoomerTransparent = conf.ZoomerOpacity < 1; + 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 WindowDetails _selectedCaptureWindow; + private bool _mouseDown; + private Rectangle _captureRect = Rectangle.Empty; + private readonly ICapture _capture; + private readonly Image _capturedImage; + private Point _previousMousePos = Point.Empty; + private FixMode _fixMode = FixMode.None; + private RectangleAnimator _windowAnimator; + private RectangleAnimator _zoomAnimator; + private readonly bool _isZoomerTransparent = Conf.ZoomerOpacity < 1; /// /// Property to access the selected capture rectangle /// public Rectangle CaptureRectangle { get { - return captureRect; + return _captureRect; } } @@ -90,7 +87,7 @@ namespace Greenshot.Forms { /// public CaptureMode UsedCaptureMode { get { - return captureMode; + return _captureMode; } } @@ -99,7 +96,7 @@ namespace Greenshot.Forms { /// public WindowDetails SelectedCaptureWindow { get { - return selectedCaptureWindow; + return _selectedCaptureWindow; } } @@ -120,14 +117,14 @@ namespace Greenshot.Forms { /// /// /// - public CaptureForm(ICapture capture, List windows) : base() { - if (currentForm != null) { + public CaptureForm(ICapture capture, List windows) { + if (_currentForm != null) { LOG.Debug("Found currentForm, Closing already opened CaptureForm"); - currentForm.Close(); - currentForm = null; + _currentForm.Close(); + _currentForm = null; Application.DoEvents(); } - currentForm = this; + _currentForm = this; // Enable the AnimatingForm EnableAnimation = true; @@ -135,56 +132,56 @@ namespace Greenshot.Forms { // Using 32bppPArgb speeds up the drawing. //capturedImage = ImageHelper.Clone(capture.Image, PixelFormat.Format32bppPArgb); // comment the clone, uncomment the assignment and the original bitmap is used. - capturedImage = capture.Image; + _capturedImage = capture.Image; // clean up - this.FormClosed += delegate { - currentForm = null; + FormClosed += delegate { + _currentForm = null; LOG.Debug("Remove CaptureForm from currentForm"); }; - this.capture = capture; - this.windows = windows; - this.captureMode = capture.CaptureDetails.CaptureMode; + _capture = capture; + _windows = windows; + _captureMode = capture.CaptureDetails.CaptureMode; // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // Only double-buffer when we are not in a TerminalServerSession - this.DoubleBuffered = !isTerminalServerSession; - this.Text = "Greenshot capture form"; + DoubleBuffered = !isTerminalServerSession; + Text = "Greenshot capture form"; // Make sure we never capture the captureform - WindowDetails.RegisterIgnoreHandle(this.Handle); + WindowDetails.RegisterIgnoreHandle(Handle); // Unregister at close - this.FormClosing += delegate { + FormClosing += delegate { // remove the buffer if it was created inside this form - if (capturedImage != capture.Image) { - capturedImage.Dispose(); + if (_capturedImage != capture.Image) { + _capturedImage.Dispose(); } LOG.Debug("Closing captureform"); - WindowDetails.UnregisterIgnoreHandle(this.Handle); + WindowDetails.UnregisterIgnoreHandle(Handle); }; // set cursor location - cursorPos = WindowCapture.GetCursorLocationRelativeToScreenBounds(); + _cursorPos = WindowCapture.GetCursorLocationRelativeToScreenBounds(); // Initialize the animations, the window capture zooms out from the cursor to the window under the cursor - if (captureMode == CaptureMode.Window) { - windowAnimator = new RectangleAnimator(new Rectangle(cursorPos, Size.Empty), captureRect, FramesForMillis(700), EasingType.Quintic, EasingMode.EaseOut); + if (_captureMode == CaptureMode.Window) { + _windowAnimator = new RectangleAnimator(new Rectangle(_cursorPos, Size.Empty), _captureRect, FramesForMillis(700), EasingType.Quintic, EasingMode.EaseOut); } // Set the zoomer animation - InitializeZoomer(conf.ZoomerEnabled); + InitializeZoomer(Conf.ZoomerEnabled); - this.SuspendLayout(); - this.Bounds = capture.ScreenBounds; - this.ResumeLayout(); + SuspendLayout(); + Bounds = capture.ScreenBounds; + ResumeLayout(); // Fix missing focus - WindowDetails.ToForeground(this.Handle); - this.TopMost = true; + WindowDetails.ToForeground(Handle); + TopMost = true; } /// @@ -193,17 +190,17 @@ namespace Greenshot.Forms { void InitializeZoomer(bool isOn) { if (isOn) { // Initialize the zoom with a invalid position - zoomAnimator = new RectangleAnimator(Rectangle.Empty, new Rectangle(int.MaxValue, int.MaxValue, 0, 0), FramesForMillis(1000), EasingType.Quintic, EasingMode.EaseOut); - VerifyZoomAnimation(cursorPos, false); - } else if (zoomAnimator != null) { - zoomAnimator.ChangeDestination(new Rectangle(Point.Empty, Size.Empty), FramesForMillis(1000)); + _zoomAnimator = new RectangleAnimator(Rectangle.Empty, new Rectangle(int.MaxValue, int.MaxValue, 0, 0), FramesForMillis(1000), EasingType.Quintic, EasingMode.EaseOut); + VerifyZoomAnimation(_cursorPos, false); + } else if (_zoomAnimator != null) { + _zoomAnimator.ChangeDestination(new Rectangle(Point.Empty, Size.Empty), FramesForMillis(1000)); } } #region key handling void CaptureFormKeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey) { - fixMode = FixMode.None; + _fixMode = FixMode.None; } } @@ -228,9 +225,8 @@ namespace Greenshot.Forms { break; case Keys.ShiftKey: // Fixmode - if (fixMode == FixMode.None) { - fixMode = FixMode.Initiated; - return; + if (_fixMode == FixMode.None) { + _fixMode = FixMode.Initiated; } break; case Keys.Escape: @@ -239,7 +235,7 @@ namespace Greenshot.Forms { break; case Keys.M: // Toggle mouse cursor - capture.CursorVisible = !capture.CursorVisible; + _capture.CursorVisible = !_capture.CursorVisible; Invalidate(); break; //// TODO: Enable when the screen capture code works reliable @@ -253,43 +249,43 @@ namespace Greenshot.Forms { // Invalidate(); // break; case Keys.Z: - if (captureMode == CaptureMode.Region) { + if (_captureMode == CaptureMode.Region) { // Toggle zoom - conf.ZoomerEnabled = !conf.ZoomerEnabled; - InitializeZoomer(conf.ZoomerEnabled); + Conf.ZoomerEnabled = !Conf.ZoomerEnabled; + InitializeZoomer(Conf.ZoomerEnabled); Invalidate(); } break; case Keys.Space: // Toggle capture mode - switch (captureMode) { + switch (_captureMode) { case CaptureMode.Region: // Set the window capture mode - captureMode = CaptureMode.Window; + _captureMode = CaptureMode.Window; // "Fade out" Zoom InitializeZoomer(false); // "Fade in" window - windowAnimator = new RectangleAnimator(new Rectangle(cursorPos, Size.Empty), captureRect, FramesForMillis(700), EasingType.Quintic, EasingMode.EaseOut); - captureRect = Rectangle.Empty; + _windowAnimator = new RectangleAnimator(new Rectangle(_cursorPos, Size.Empty), _captureRect, FramesForMillis(700), EasingType.Quintic, EasingMode.EaseOut); + _captureRect = Rectangle.Empty; Invalidate(); break; case CaptureMode.Window: // Set the region capture mode - captureMode = CaptureMode.Region; + _captureMode = CaptureMode.Region; // "Fade out" window - windowAnimator.ChangeDestination(new Rectangle(cursorPos, Size.Empty), FramesForMillis(700)); + _windowAnimator.ChangeDestination(new Rectangle(_cursorPos, Size.Empty), FramesForMillis(700)); // Fade in zoom - InitializeZoomer(conf.ZoomerEnabled); - captureRect = Rectangle.Empty; + InitializeZoomer(Conf.ZoomerEnabled); + _captureRect = Rectangle.Empty; Invalidate(); break; } - selectedCaptureWindow = null; + _selectedCaptureWindow = null; OnMouseMove(this, new MouseEventArgs(MouseButtons.None, 0, Cursor.Position.X, Cursor.Position.Y, 0)); break; case Keys.Return: // Confirm - if (captureMode == CaptureMode.Window) { + if (_captureMode == CaptureMode.Window) { DialogResult = DialogResult.OK; } break; @@ -306,9 +302,9 @@ namespace Greenshot.Forms { void OnMouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point tmpCursorLocation = WindowCapture.GetCursorLocationRelativeToScreenBounds(); - mX = tmpCursorLocation.X; - mY = tmpCursorLocation.Y; - mouseDown = true; + _mX = tmpCursorLocation.X; + _mY = tmpCursorLocation.Y; + _mouseDown = true; OnMouseMove(this, e); Invalidate(); } @@ -320,18 +316,18 @@ namespace Greenshot.Forms { /// /// void OnMouseUp(object sender, MouseEventArgs e) { - if (mouseDown) { + if (_mouseDown) { // If the mouse goes up we set down to false (nice logic!) - mouseDown = false; + _mouseDown = false; // Check if anything is selected - if (captureMode == CaptureMode.Window && selectedCaptureWindow != null) { + if (_captureMode == CaptureMode.Window && _selectedCaptureWindow != null) { // Go and process the capture DialogResult = DialogResult.OK; - } else if (captureRect.Height > 0 && captureRect.Width > 0) { + } else if (_captureRect.Height > 0 && _captureRect.Width > 0) { // correct the GUI width to real width if Region mode - if (captureMode == CaptureMode.Region) { - captureRect.Width += 1; - captureRect.Height += 1; + if (_captureMode == CaptureMode.Region) { + _captureRect.Width += 1; + _captureRect.Height += 1; } // Go and process the capture DialogResult = DialogResult.OK; @@ -347,18 +343,18 @@ namespace Greenshot.Forms { /// /// private Point FixMouseCoordinates(Point currentMouse) { - if (fixMode == FixMode.Initiated) { - if (previousMousePos.X != currentMouse.X) { - fixMode = FixMode.Vertical; - } else if (previousMousePos.Y != currentMouse.Y) { - fixMode = FixMode.Horizontal; + if (_fixMode == FixMode.Initiated) { + if (_previousMousePos.X != currentMouse.X) { + _fixMode = FixMode.Vertical; + } else if (_previousMousePos.Y != currentMouse.Y) { + _fixMode = FixMode.Horizontal; } - } else if (fixMode == FixMode.Vertical) { - currentMouse = new Point(currentMouse.X, previousMousePos.Y); - } else if (fixMode == FixMode.Horizontal) { - currentMouse = new Point(previousMousePos.X, currentMouse.Y); + } else if (_fixMode == FixMode.Vertical) { + currentMouse = new Point(currentMouse.X, _previousMousePos.Y); + } else if (_fixMode == FixMode.Horizontal) { + currentMouse = new Point(_previousMousePos.X, currentMouse.Y); } - previousMousePos = currentMouse; + _previousMousePos = currentMouse; return currentMouse; } @@ -369,8 +365,8 @@ namespace Greenshot.Forms { /// void OnMouseMove(object sender, MouseEventArgs e) { // Make sure the mouse coordinates are fixed, when pressing shift - mouseMovePos = FixMouseCoordinates(WindowCapture.GetCursorLocation()); - mouseMovePos = WindowCapture.GetLocationRelativeToScreenBounds(mouseMovePos); + _mouseMovePos = FixMouseCoordinates(WindowCapture.GetCursorLocation()); + _mouseMovePos = WindowCapture.GetLocationRelativeToScreenBounds(_mouseMovePos); } /// @@ -389,67 +385,66 @@ namespace Greenshot.Forms { /// update the frame, this only invalidates /// protected override void Animate() { - Point lastPos = cursorPos.Clone(); - cursorPos = mouseMovePos.Clone(); + Point lastPos = _cursorPos; + _cursorPos = _mouseMovePos; - if (selectedCaptureWindow != null && lastPos.Equals(cursorPos) && !isAnimating(zoomAnimator) && !isAnimating(windowAnimator)) { + if (_selectedCaptureWindow != null && lastPos.Equals(_cursorPos) && !isAnimating(_zoomAnimator) && !isAnimating(_windowAnimator)) { return; } - Rectangle lastCaptureRect = new Rectangle(captureRect.Location, captureRect.Size); - WindowDetails lastWindow = selectedCaptureWindow; + WindowDetails lastWindow = _selectedCaptureWindow; bool horizontalMove = false; bool verticalMove = false; - if (lastPos.X != cursorPos.X) { + if (lastPos.X != _cursorPos.X) { horizontalMove = true; } - if (lastPos.Y != cursorPos.Y) { + if (lastPos.Y != _cursorPos.Y) { verticalMove = true; } - if (captureMode == CaptureMode.Region && mouseDown) { - captureRect = GuiRectangle.GetGuiRectangle(cursorPos.X, cursorPos.Y, mX - cursorPos.X, mY - cursorPos.Y); + if (_captureMode == CaptureMode.Region && _mouseDown) { + _captureRect = GuiRectangle.GetGuiRectangle(_cursorPos.X, _cursorPos.Y, _mX - _cursorPos.X, _mY - _cursorPos.Y); } // Iterate over the found windows and check if the current location is inside a window Point cursorPosition = Cursor.Position; - selectedCaptureWindow = null; - lock (windows) { - foreach (WindowDetails window in windows) { + _selectedCaptureWindow = null; + lock (_windows) { + foreach (WindowDetails window in _windows) { if (window.Contains(cursorPosition)) { // Only go over the children if we are in window mode - if (CaptureMode.Window == captureMode) { - selectedCaptureWindow = window.FindChildUnderPoint(cursorPosition); + if (CaptureMode.Window == _captureMode) { + _selectedCaptureWindow = window.FindChildUnderPoint(cursorPosition); } else { - selectedCaptureWindow = window; + _selectedCaptureWindow = window; } break; } } } - if (selectedCaptureWindow != null && !selectedCaptureWindow.Equals(lastWindow)) { - capture.CaptureDetails.Title = selectedCaptureWindow.Text; - capture.CaptureDetails.AddMetaData("windowtitle", selectedCaptureWindow.Text); - if (captureMode == CaptureMode.Window) { + if (_selectedCaptureWindow != null && !_selectedCaptureWindow.Equals(lastWindow)) { + _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; + _capture.CaptureDetails.AddMetaData("windowtitle", _selectedCaptureWindow.Text); + if (_captureMode == CaptureMode.Window) { // Here we want to capture the window which is under the mouse - captureRect = selectedCaptureWindow.WindowRectangle; + _captureRect = _selectedCaptureWindow.WindowRectangle; // As the ClientRectangle is not in Bitmap coordinates, we need to correct. - captureRect.Offset(-capture.ScreenBounds.Location.X, -capture.ScreenBounds.Location.Y); + _captureRect.Offset(-_capture.ScreenBounds.Location.X, -_capture.ScreenBounds.Location.Y); } } - Rectangle invalidateRectangle = Rectangle.Empty; - if (mouseDown && (captureMode != CaptureMode.Window)) { - int x1 = Math.Min(mX, lastPos.X); - int x2 = Math.Max(mX, lastPos.X); - int y1 = Math.Min(mY, lastPos.Y); - int y2 = Math.Max(mY, lastPos.Y); - x1= Math.Min(x1, cursorPos.X); - x2= Math.Max(x2, cursorPos.X); - y1= Math.Min(y1, cursorPos.Y); - y2= Math.Max(y2, cursorPos.Y); + Rectangle invalidateRectangle; + if (_mouseDown && (_captureMode != CaptureMode.Window)) { + int x1 = Math.Min(_mX, lastPos.X); + int x2 = Math.Max(_mX, lastPos.X); + int y1 = Math.Min(_mY, lastPos.Y); + int y2 = Math.Max(_mY, lastPos.Y); + x1= Math.Min(x1, _cursorPos.X); + x2= Math.Max(x2, _cursorPos.X); + y1= Math.Min(y1, _cursorPos.Y); + y2= Math.Max(y2, _cursorPos.Y); // Safety correction x2 += 2; @@ -458,79 +453,79 @@ namespace Greenshot.Forms { // Here we correct for text-size // Calculate the size - int textForWidth = Math.Max(Math.Abs(mX - cursorPos.X), Math.Abs(mX - lastPos.X)); - int textForHeight = Math.Max(Math.Abs(mY - cursorPos.Y), Math.Abs(mY - lastPos.Y)); + int textForWidth = Math.Max(Math.Abs(_mX - _cursorPos.X), Math.Abs(_mX - lastPos.X)); + int textForHeight = Math.Max(Math.Abs(_mY - _cursorPos.Y), Math.Abs(_mY - lastPos.Y)); using (Font rulerFont = new Font(FontFamily.GenericSansSerif, 8)) { - Size measureWidth = TextRenderer.MeasureText(textForWidth.ToString(), rulerFont); + Size measureWidth = TextRenderer.MeasureText(textForWidth.ToString(CultureInfo.InvariantCulture), rulerFont); x1 -= measureWidth.Width + 15; - Size measureHeight = TextRenderer.MeasureText(textForHeight.ToString(), rulerFont); - y1 -= measureWidth.Height + 10; + Size measureHeight = TextRenderer.MeasureText(textForHeight.ToString(CultureInfo.InvariantCulture), rulerFont); + y1 -= measureHeight.Height + 10; } invalidateRectangle = new Rectangle(x1,y1, x2-x1, y2-y1); Invalidate(invalidateRectangle); - } else if (captureMode != CaptureMode.Window) { + } else if (_captureMode != CaptureMode.Window) { if (!isTerminalServerSession) { Rectangle allScreenBounds = WindowCapture.GetScreenBounds(); allScreenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location); if (verticalMove) { // Before - invalidateRectangle = GuiRectangle.GetGuiRectangle(allScreenBounds.Left, lastPos.Y - 2, this.Width + 2, 45); + invalidateRectangle = GuiRectangle.GetGuiRectangle(allScreenBounds.Left, lastPos.Y - 2, Width + 2, 45); Invalidate(invalidateRectangle); // After - invalidateRectangle = GuiRectangle.GetGuiRectangle(allScreenBounds.Left, cursorPos.Y - 2, this.Width + 2, 45); + invalidateRectangle = GuiRectangle.GetGuiRectangle(allScreenBounds.Left, _cursorPos.Y - 2, Width + 2, 45); Invalidate(invalidateRectangle); } if (horizontalMove) { // Before - invalidateRectangle = GuiRectangle.GetGuiRectangle(lastPos.X - 2, allScreenBounds.Top, 75, this.Height + 2); + invalidateRectangle = GuiRectangle.GetGuiRectangle(lastPos.X - 2, allScreenBounds.Top, 75, Height + 2); Invalidate(invalidateRectangle); // After - invalidateRectangle = GuiRectangle.GetGuiRectangle(cursorPos.X - 2, allScreenBounds.Top, 75, this.Height + 2); + invalidateRectangle = GuiRectangle.GetGuiRectangle(_cursorPos.X - 2, allScreenBounds.Top, 75, Height + 2); Invalidate(invalidateRectangle); } } } else { - if (selectedCaptureWindow != null && !selectedCaptureWindow.Equals(lastWindow)) { + if (_selectedCaptureWindow != null && !_selectedCaptureWindow.Equals(lastWindow)) { // Window changes, make new animation from current to target - windowAnimator.ChangeDestination(captureRect, FramesForMillis(700)); + _windowAnimator.ChangeDestination(_captureRect, FramesForMillis(700)); } } // always animate the Window area through to the last frame, so we see the fade-in/out untill the end // Using a safety "offset" to make sure the text is invalidated too - const int SAFETY_SIZE = 30; + const int safetySize = 30; // Check if the - if (isAnimating(windowAnimator)) { - invalidateRectangle = windowAnimator.Current; - invalidateRectangle.Inflate(SAFETY_SIZE, SAFETY_SIZE); + if (isAnimating(_windowAnimator)) { + invalidateRectangle = _windowAnimator.Current; + invalidateRectangle.Inflate(safetySize, safetySize); Invalidate(invalidateRectangle); - invalidateRectangle = windowAnimator.Next(); - invalidateRectangle.Inflate(SAFETY_SIZE, SAFETY_SIZE); + invalidateRectangle = _windowAnimator.Next(); + invalidateRectangle.Inflate(safetySize, safetySize); Invalidate(invalidateRectangle); // Check if this was the last of the windows animations in the normal region capture. - if (captureMode != CaptureMode.Window && !isAnimating(windowAnimator)) { + if (_captureMode != CaptureMode.Window && !isAnimating(_windowAnimator)) { Invalidate(); } } - if (zoomAnimator != null && (isAnimating(zoomAnimator) || captureMode != CaptureMode.Window)) { + if (_zoomAnimator != null && (isAnimating(_zoomAnimator) || _captureMode != CaptureMode.Window)) { // Make sure we invalidate the old zoom area - invalidateRectangle = zoomAnimator.Current; + invalidateRectangle = _zoomAnimator.Current; invalidateRectangle.Offset(lastPos); Invalidate(invalidateRectangle); // Only verify if we are really showing the zoom, not the outgoing animation - if (conf.ZoomerEnabled && captureMode != CaptureMode.Window) { - VerifyZoomAnimation(cursorPos, false); + if (Conf.ZoomerEnabled && _captureMode != CaptureMode.Window) { + VerifyZoomAnimation(_cursorPos, false); } // The following logic is not needed, next always returns the current if there are no frames left // but it makes more sense if we want to change something in the logic - if (isAnimating(zoomAnimator)) { - invalidateRectangle = zoomAnimator.Next(); + if (isAnimating(_zoomAnimator)) { + invalidateRectangle = _zoomAnimator.Next(); } else { - invalidateRectangle = zoomAnimator.Current; + invalidateRectangle = _zoomAnimator.Current; } - invalidateRectangle.Offset(cursorPos); + invalidateRectangle.Offset(_cursorPos); Invalidate(invalidateRectangle); } // Force update "now" @@ -559,27 +554,27 @@ namespace Greenshot.Forms { Size zoomSize = new Size(relativeZoomSize, relativeZoomSize); Point zoomOffset = new Point(20, 20); - Rectangle targetRectangle = zoomAnimator.Final; + Rectangle targetRectangle = _zoomAnimator.Final; targetRectangle.Offset(pos); - if (!screenBounds.Contains(targetRectangle) || (!allowZoomOverCaptureRect && captureRect.IntersectsWith(targetRectangle))) { + if (!screenBounds.Contains(targetRectangle) || (!allowZoomOverCaptureRect && _captureRect.IntersectsWith(targetRectangle))) { Point destinationLocation = Point.Empty; Rectangle tl = new Rectangle(pos.X - (zoomOffset.X + zoomSize.Width), pos.Y - (zoomOffset.Y + zoomSize.Height), zoomSize.Width, zoomSize.Height); Rectangle tr = new Rectangle(pos.X + zoomOffset.X, pos.Y - (zoomOffset.Y + zoomSize.Height), zoomSize.Width, zoomSize.Height); Rectangle bl = new Rectangle(pos.X - (zoomOffset.X + zoomSize.Width), pos.Y + zoomOffset.Y, zoomSize.Width, zoomSize.Height); Rectangle br = new Rectangle(pos.X + zoomOffset.X, pos.Y + zoomOffset.Y, zoomSize.Width, zoomSize.Height); - if (screenBounds.Contains(br) && (allowZoomOverCaptureRect || !captureRect.IntersectsWith(br))) { + if (screenBounds.Contains(br) && (allowZoomOverCaptureRect || !_captureRect.IntersectsWith(br))) { destinationLocation = new Point(zoomOffset.X, zoomOffset.Y); - } else if (screenBounds.Contains(bl) && (allowZoomOverCaptureRect || !captureRect.IntersectsWith(bl))) { + } else if (screenBounds.Contains(bl) && (allowZoomOverCaptureRect || !_captureRect.IntersectsWith(bl))) { destinationLocation = new Point(-zoomOffset.X - zoomSize.Width, zoomOffset.Y); - } else if (screenBounds.Contains(tr) && (allowZoomOverCaptureRect || !captureRect.IntersectsWith(tr))) { + } else if (screenBounds.Contains(tr) && (allowZoomOverCaptureRect || !_captureRect.IntersectsWith(tr))) { destinationLocation = new Point(zoomOffset.X, -zoomOffset.Y - zoomSize.Width); - } else if (screenBounds.Contains(tl) && (allowZoomOverCaptureRect || !captureRect.IntersectsWith(tl))) { + } else if (screenBounds.Contains(tl) && (allowZoomOverCaptureRect || !_captureRect.IntersectsWith(tl))) { destinationLocation = new Point(-zoomOffset.X - zoomSize.Width, -zoomOffset.Y - zoomSize.Width); } if (destinationLocation == Point.Empty && !allowZoomOverCaptureRect) { VerifyZoomAnimation(pos, true); } else { - zoomAnimator.ChangeDestination(new Rectangle(destinationLocation, zoomSize)); + _zoomAnimator.ChangeDestination(new Rectangle(destinationLocation, zoomSize)); } } } @@ -591,15 +586,15 @@ namespace Greenshot.Forms { /// /// private void DrawZoom(Graphics graphics, Rectangle sourceRectangle, Rectangle destinationRectangle) { - if (capturedImage == null) { + if (_capturedImage == null) { return; } ImageAttributes attributes; - if (isZoomerTransparent) { + if (_isZoomerTransparent) { //create a color matrix object to change the opacy ColorMatrix opacyMatrix = new ColorMatrix(); - opacyMatrix.Matrix33 = conf.ZoomerOpacity; + opacyMatrix.Matrix33 = Conf.ZoomerOpacity; attributes = new ImageAttributes(); attributes.SetColorMatrix(opacyMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); } else { @@ -614,14 +609,14 @@ namespace Greenshot.Forms { using (GraphicsPath path = new GraphicsPath()) { path.AddEllipse(destinationRectangle); graphics.SetClip(path); - if (!isZoomerTransparent) { - graphics.FillRectangle(backgroundBrush, destinationRectangle); - graphics.DrawImage(capturedImage, destinationRectangle, sourceRectangle, GraphicsUnit.Pixel); + if (!_isZoomerTransparent) { + graphics.FillRectangle(BackgroundBrush, destinationRectangle); + graphics.DrawImage(_capturedImage, destinationRectangle, sourceRectangle, GraphicsUnit.Pixel); } else { - graphics.DrawImage(capturedImage, destinationRectangle, sourceRectangle.X, sourceRectangle.Y, sourceRectangle.Width, sourceRectangle.Height, GraphicsUnit.Pixel, attributes); + graphics.DrawImage(_capturedImage, destinationRectangle, sourceRectangle.X, sourceRectangle.Y, sourceRectangle.Width, sourceRectangle.Height, GraphicsUnit.Pixel, attributes); } } - int alpha = (int)(255 * conf.ZoomerOpacity); + int alpha = (int)(255 * Conf.ZoomerOpacity); Color opacyWhite = Color.FromArgb(alpha, 255, 255, 255); Color opacyBlack = Color.FromArgb(alpha, 0, 0, 0); @@ -685,22 +680,22 @@ namespace Greenshot.Forms { Graphics graphics = e.Graphics; Rectangle clipRectangle = e.ClipRectangle; //graphics.BitBlt((Bitmap)buffer, Point.Empty); - graphics.DrawImageUnscaled(capturedImage, Point.Empty); + graphics.DrawImageUnscaled(_capturedImage, Point.Empty); // Only draw Cursor if it's (partly) visible - if (capture.Cursor != null && capture.CursorVisible && clipRectangle.IntersectsWith(new Rectangle(capture.CursorLocation, capture.Cursor.Size))) { - graphics.DrawIcon(capture.Cursor, capture.CursorLocation.X, capture.CursorLocation.Y); + if (_capture.Cursor != null && _capture.CursorVisible && clipRectangle.IntersectsWith(new Rectangle(_capture.CursorLocation, _capture.Cursor.Size))) { + graphics.DrawIcon(_capture.Cursor, _capture.CursorLocation.X, _capture.CursorLocation.Y); } - if (mouseDown || captureMode == CaptureMode.Window || isAnimating(windowAnimator)) { - captureRect.Intersect(new Rectangle(Point.Empty, capture.ScreenBounds.Size)); // crop what is outside the screen + if (_mouseDown || _captureMode == CaptureMode.Window || isAnimating(_windowAnimator)) { + _captureRect.Intersect(new Rectangle(Point.Empty, _capture.ScreenBounds.Size)); // crop what is outside the screen Rectangle fixedRect; //if (captureMode == CaptureMode.Window) { - if (isAnimating(windowAnimator)) { + if (isAnimating(_windowAnimator)) { // Use the animator - fixedRect = windowAnimator.Current; + fixedRect = _windowAnimator.Current; } else { - fixedRect = captureRect; + fixedRect = _captureRect; } // TODO: enable when the screen capture code works reliable @@ -712,17 +707,17 @@ namespace Greenshot.Forms { graphics.DrawRectangle(OverlayPen, fixedRect); // rulers - int dist = 8; + const int dist = 8; string captureWidth; string captureHeight; // The following fixes the very old incorrect size information bug - if (captureMode == CaptureMode.Window) { - captureWidth = captureRect.Width.ToString(); - captureHeight = captureRect.Height.ToString(); + if (_captureMode == CaptureMode.Window) { + captureWidth = _captureRect.Width.ToString(CultureInfo.InvariantCulture); + captureHeight = _captureRect.Height.ToString(CultureInfo.InvariantCulture); } else { - captureWidth = (captureRect.Width + 1).ToString(); - captureHeight = (captureRect.Height + 1).ToString(); + captureWidth = (_captureRect.Width + 1).ToString(CultureInfo.InvariantCulture); + captureHeight = (_captureRect.Height + 1).ToString(CultureInfo.InvariantCulture); } using (Font rulerFont = new Font(FontFamily.GenericSansSerif, 8)) { Size measureWidth = TextRenderer.MeasureText(captureWidth, rulerFont); @@ -734,7 +729,7 @@ namespace Greenshot.Forms { // horizontal ruler if (fixedRect.Width > hSpace + 3) { - using (GraphicsPath p = Drawing.RoundedRectangle.Create2( + using (GraphicsPath p = RoundedRectangle.Create2( fixedRect.X + (fixedRect.Width / 2 - hSpace / 2) + 3, fixedRect.Y - dist - 7, measureWidth.Width - 3, @@ -752,7 +747,7 @@ namespace Greenshot.Forms { // vertical ruler if (fixedRect.Height > vSpace + 3) { - using (GraphicsPath p = Drawing.RoundedRectangle.Create2( + using (GraphicsPath p = RoundedRectangle.Create2( fixedRect.X - measureHeight.Width + 1, fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2) + 2, measureHeight.Width - 3, @@ -776,18 +771,18 @@ namespace Greenshot.Forms { // Prepare the font and text. using (Font sizeFont = new Font( FontFamily.GenericSansSerif, 12 )) { // When capturing a Region we need to add 1 to the height/width for correction - string sizeText = null; - if (captureMode == CaptureMode.Region) { + 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; + sizeText = _captureRect.Width + " x " + _captureRect.Height; } // Calculate the scaled font size. SizeF extent = graphics.MeasureString( sizeText, sizeFont ); - float hRatio = captureRect.Height / (extent.Height * 2); - float wRatio = captureRect.Width / (extent.Width * 2); + float hRatio = _captureRect.Height / (extent.Height * 2); + float wRatio = _captureRect.Width / (extent.Width * 2); float ratio = ( hRatio < wRatio ? hRatio : wRatio ); float newSize = sizeFont.Size * ratio; @@ -798,8 +793,8 @@ 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) - (sizeFont.GetHeight() / 2)); - graphics.DrawString(sizeText, sizeFont, Brushes.LightSeaGreen, sizeLocation); + 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); } } } @@ -807,21 +802,21 @@ namespace Greenshot.Forms { if (!isTerminalServerSession) { using (Pen pen = new Pen(Color.LightSeaGreen)) { pen.DashStyle = DashStyle.Dot; - Rectangle screenBounds = capture.ScreenBounds; - graphics.DrawLine(pen, cursorPos.X, screenBounds.Y, cursorPos.X, screenBounds.Height); - graphics.DrawLine(pen, screenBounds.X, cursorPos.Y, screenBounds.Width, cursorPos.Y); + Rectangle screenBounds = _capture.ScreenBounds; + graphics.DrawLine(pen, _cursorPos.X, screenBounds.Y, _cursorPos.X, screenBounds.Height); + graphics.DrawLine(pen, screenBounds.X, _cursorPos.Y, screenBounds.Width, _cursorPos.Y); } - string xy = cursorPos.X + " x " + cursorPos.Y; + string xy = _cursorPos.X + " x " + _cursorPos.Y; using (Font f = new Font(FontFamily.GenericSansSerif, 8)) { Size xySize = TextRenderer.MeasureText(xy, f); - using (GraphicsPath gp = Drawing.RoundedRectangle.Create2(cursorPos.X + 5, cursorPos.Y + 5, xySize.Width - 3, xySize.Height, 3)) { + using (GraphicsPath gp = RoundedRectangle.Create2(_cursorPos.X + 5, _cursorPos.Y + 5, xySize.Width - 3, xySize.Height, 3)) { using (Brush bgBrush = new SolidBrush(Color.FromArgb(200, 217, 240, 227))) { graphics.FillPath(bgBrush, gp); } using (Pen pen = new Pen(Color.SeaGreen)) { graphics.DrawPath(pen, gp); - Point coordinatePosition = new Point(cursorPos.X + 5, cursorPos.Y + 5); + Point coordinatePosition = new Point(_cursorPos.X + 5, _cursorPos.Y + 5); graphics.DrawString(xy, f, pen.Brush, coordinatePosition); } } @@ -830,14 +825,14 @@ namespace Greenshot.Forms { } // Zoom - if (zoomAnimator != null && (isAnimating(zoomAnimator) || captureMode != CaptureMode.Window)) { + if (_zoomAnimator != null && (isAnimating(_zoomAnimator) || _captureMode != CaptureMode.Window)) { 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); + Rectangle destinationRectangle = _zoomAnimator.Current; + destinationRectangle.Offset(_cursorPos); DrawZoom(graphics, sourceRectangle, destinationRectangle); } } diff --git a/Greenshot/Forms/ColorDialog.cs b/Greenshot/Forms/ColorDialog.cs index 313d05d3e..57beb84cf 100644 --- a/Greenshot/Forms/ColorDialog.cs +++ b/Greenshot/Forms/ColorDialog.cs @@ -21,11 +21,12 @@ using System; using System.Collections.Generic; using System.Drawing; +using System.Globalization; using System.Threading; using System.Windows.Forms; using Greenshot.Configuration; -using GreenshotPlugin.Core; +using Greenshot.Controls; using Greenshot.IniFile; namespace Greenshot { @@ -37,12 +38,12 @@ namespace Greenshot { private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); private ColorDialog() { - this.SuspendLayout(); + SuspendLayout(); InitializeComponent(); - this.SuspendLayout(); - this.createColorPalette(5,5,15,15); - this.createLastUsedColorButtonRow(5,190,15,15); - this.ResumeLayout(); + SuspendLayout(); + createColorPalette(5,5,15,15); + createLastUsedColorButtonRow(5,190,15,15); + ResumeLayout(); updateRecentColorsButtonRow(); } @@ -65,33 +66,33 @@ namespace Greenshot { #region user interface generation private void createColorPalette(int x, int y, int w, int h) { - this.createColorButtonColumn(255,0,0, x, y, w, h, 11); + createColorButtonColumn(255,0,0, x, y, w, h, 11); x += w; - this.createColorButtonColumn(255,255/2,0, x, y, w, h, 11); + createColorButtonColumn(255,255/2,0, x, y, w, h, 11); x += w; - this.createColorButtonColumn(255,255,0, x, y, w, h, 11); + createColorButtonColumn(255,255,0, x, y, w, h, 11); x += w; - this.createColorButtonColumn(255/2,255,0, x, y, w, h, 11); + createColorButtonColumn(255/2,255,0, x, y, w, h, 11); x += w; - this.createColorButtonColumn(0,255,0, x, y, w, h, 11); + createColorButtonColumn(0,255,0, x, y, w, h, 11); x += w; - this.createColorButtonColumn(0,255,255/2, x, y, w, h, 11); + createColorButtonColumn(0,255,255/2, x, y, w, h, 11); x += w; - this.createColorButtonColumn(0,255,255, x, y, w, h, 11); + createColorButtonColumn(0,255,255, x, y, w, h, 11); x += w; - this.createColorButtonColumn(0,255/2,255, x, y, w, h, 11); + createColorButtonColumn(0,255/2,255, x, y, w, h, 11); x += w; - this.createColorButtonColumn(0,0,255, x, y, w, h, 11); + createColorButtonColumn(0,0,255, x, y, w, h, 11); x += w; - this.createColorButtonColumn(255/2,0,255, x, y, w, h, 11); + createColorButtonColumn(255/2,0,255, x, y, w, h, 11); x += w; - this.createColorButtonColumn(255,0,255, x, y, w, h, 11); + createColorButtonColumn(255,0,255, x, y, w, h, 11); x += w; - this.createColorButtonColumn(255,0,255/2, x, y, w, h, 11); + createColorButtonColumn(255,0,255/2, x, y, w, h, 11); x += w + 5; - this.createColorButtonColumn(255/2,255/2,255/2, x, y, w, h, 11); + createColorButtonColumn(255/2,255/2,255/2, x, y, w, h, 11); - this.Controls.AddRange(this.colorButtons.ToArray()); + Controls.AddRange(colorButtons.ToArray()); } private void createColorButtonColumn(int red, int green, int blue, int x, int y, int w, int h, int shades) { int shadedColorsNum = (shades - 1) / 2; @@ -111,18 +112,18 @@ namespace Greenshot { b.Location = new Point(x,y); b.Size = new Size(w,h); b.TabStop = false; - b.Click += new System.EventHandler(colorButtonClick); + b.Click += colorButtonClick; toolTip.SetToolTip(b,ColorTranslator.ToHtml(color)+" | R:"+color.R +", G:"+color.G+", B:"+color.B); return b; } private void createLastUsedColorButtonRow(int x, int y, int w, int h) { for(int i=0; i<12; i++) { - Button b = this.createColorButton(Color.Transparent, x, y, w, h); + Button b = createColorButton(Color.Transparent, x, y, w, h); b.Enabled = false; recentColorButtons.Add(b); x += w; } - this.Controls.AddRange(this.recentColorButtons.ToArray()); + Controls.AddRange(recentColorButtons.ToArray()); } #endregion @@ -136,22 +137,22 @@ namespace Greenshot { private void previewColor(Color c, Control trigger) { updateInProgress = true; - this.colorPanel.BackColor = c; - if(trigger != this.textBoxHtmlColor) { - this.textBoxHtmlColor.Text = System.Drawing.ColorTranslator.ToHtml(c); + colorPanel.BackColor = c; + if(trigger != textBoxHtmlColor) { + textBoxHtmlColor.Text = ColorTranslator.ToHtml(c); } else { - if(!this.textBoxHtmlColor.Text.StartsWith("#")) { - int selStart = this.textBoxHtmlColor.SelectionStart; - int selLength = this.textBoxHtmlColor.SelectionLength; - this.textBoxHtmlColor.Text = "#" +this.textBoxHtmlColor.Text; - this.textBoxHtmlColor.Select(selStart+1, selLength+1); + if(!textBoxHtmlColor.Text.StartsWith("#")) { + int selStart = textBoxHtmlColor.SelectionStart; + int selLength = textBoxHtmlColor.SelectionLength; + textBoxHtmlColor.Text = "#" +textBoxHtmlColor.Text; + textBoxHtmlColor.Select(selStart+1, selLength+1); } } - if(trigger != this.textBoxRed && trigger != this.textBoxGreen && trigger != this.textBoxBlue && trigger != this.textBoxAlpha) { - this.textBoxRed.Text = c.R.ToString(); - this.textBoxGreen.Text = c.G.ToString(); - this.textBoxBlue.Text = c.B.ToString(); - this.textBoxAlpha.Text = c.A.ToString(); + if(trigger != textBoxRed && trigger != textBoxGreen && trigger != textBoxBlue && trigger != textBoxAlpha) { + textBoxRed.Text = c.R.ToString(); + textBoxGreen.Text = c.G.ToString(); + textBoxBlue.Text = c.B.ToString(); + textBoxAlpha.Text = c.A.ToString(); } updateInProgress = false; } @@ -165,25 +166,25 @@ namespace Greenshot { #endregion #region textbox event handlers - void TextBoxHexadecimalTextChanged(object sender, System.EventArgs e) + void TextBoxHexadecimalTextChanged(object sender, EventArgs e) { if(updateInProgress) return; TextBox tb = (TextBox) sender; string t = tb.Text.Replace("#",""); int i = 0; - Int32.TryParse(t, System.Globalization.NumberStyles.AllowHexSpecifier, Thread.CurrentThread.CurrentCulture, out i); + Int32.TryParse(t, NumberStyles.AllowHexSpecifier, Thread.CurrentThread.CurrentCulture, out i); Color c = Color.FromArgb(i); Color opaqueColor = Color.FromArgb(255, c.R, c.G, c.B); previewColor(opaqueColor, tb); } - void TextBoxRGBTextChanged(object sender, System.EventArgs e) + void TextBoxRGBTextChanged(object sender, EventArgs e) { if(updateInProgress) return; TextBox tb = (TextBox) sender; previewColor(Color.FromArgb(getColorPartIntFromString(textBoxAlpha.Text),getColorPartIntFromString(textBoxRed.Text),getColorPartIntFromString(textBoxGreen.Text),getColorPartIntFromString(textBoxBlue.Text)), tb); } - void TextBoxGotFocus(object sender, System.EventArgs e) { - this.textBoxHtmlColor.SelectAll(); + void TextBoxGotFocus(object sender, EventArgs e) { + textBoxHtmlColor.SelectAll(); } void TextBoxKeyDown(object sender, KeyEventArgs e) { if(e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter) { @@ -193,19 +194,19 @@ namespace Greenshot { #endregion #region button event handlers - void colorButtonClick(object sender, System.EventArgs e) { + void colorButtonClick(object sender, EventArgs e) { Button b = (Button) sender; previewColor(b.BackColor, b); } - void btnTransparentClick(object sender, System.EventArgs e) + void btnTransparentClick(object sender, EventArgs e) { colorButtonClick(sender, e); } - void BtnApplyClick(object sender, System.EventArgs e) + void BtnApplyClick(object sender, EventArgs e) { - this.DialogResult = DialogResult.OK; - this.Hide(); + DialogResult = DialogResult.OK; + Hide(); addToRecentColors(colorPanel.BackColor); } #endregion @@ -221,8 +222,8 @@ namespace Greenshot { #endregion - private void pipetteUsed(object sender, Greenshot.Controls.PipetteUsedArgs e) { - this.Color = e.color; + private void pipetteUsed(object sender, PipetteUsedArgs e) { + Color = e.color; } } } diff --git a/Greenshot/Forms/ImageEditorForm.cs b/Greenshot/Forms/ImageEditorForm.cs index 6806dd8cf..f3544202d 100644 --- a/Greenshot/Forms/ImageEditorForm.cs +++ b/Greenshot/Forms/ImageEditorForm.cs @@ -32,29 +32,28 @@ using Greenshot.Destinations; using Greenshot.Drawing; using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields.Binding; -using Greenshot.Forms; using Greenshot.Help; using Greenshot.Helpers; using Greenshot.Plugin; +using GreenshotPlugin.Controls; using GreenshotPlugin.Core; using Greenshot.IniFile; using System.Threading; -using System.Drawing.Imaging; -using Greenshot.Plugin.Drawing; using Greenshot.Core; +using log4net; namespace Greenshot { /// /// Description of ImageEditorForm. /// public partial class ImageEditorForm : BaseForm, IImageEditor { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImageEditorForm)); + 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 Surface surface; - private GreenshotPlugin.Controls.GreenshotToolStripButton[] toolbarButtons; + private GreenshotToolStripButton[] toolbarButtons; private static string[] SUPPORTED_CLIPBOARD_FORMATS = {typeof(string).FullName, "Text", typeof(DrawableContainerList).FullName}; @@ -83,17 +82,17 @@ namespace Greenshot { // // The InitializeComponent() call is required for Windows Forms designer support. // - this.ManualLanguageApply = true; + ManualLanguageApply = true; InitializeComponent(); - this.Load += delegate { + Load += delegate { var thread = new Thread(delegate() {AddDestinations();}); thread.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(this.Handle); + WindowDetails thisForm = new WindowDetails(Handle); thisForm.WindowPlacement = editorConfiguration.GetEditorPlacement(); // init surface @@ -113,8 +112,8 @@ namespace Greenshot { private void RemoveSurface() { if (surface != null) { panel1.Controls.Remove(surface as Control); - this.surface.Dispose(); - this.surface = null; + surface.Dispose(); + surface = null; } } @@ -123,7 +122,7 @@ namespace Greenshot { /// /// private void SetSurface(ISurface newSurface) { - if (this.Surface != null && this.Surface.Modified) { + if (Surface != null && Surface.Modified) { throw new ApplicationException("Surface modified"); } @@ -131,31 +130,31 @@ namespace Greenshot { panel1.Height = 10; panel1.Width = 10; - this.surface = newSurface as Surface; + surface = newSurface as Surface; panel1.Controls.Add(surface as Surface); - Image backgroundForTransparency = GreenshotPlugin.Core.GreenshotResources.getImage("Checkerboard.Image"); - this.surface.TransparencyBackgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile); + Image backgroundForTransparency = GreenshotResources.getImage("Checkerboard.Image"); + surface.TransparencyBackgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile); surface.MovingElementChanged += delegate { refreshEditorControls(); }; - surface.DrawingModeChanged += new SurfaceDrawingModeEventHandler(surface_DrawingModeChanged); - surface.SurfaceSizeChanged += new SurfaceSizeChangeEventHandler(SurfaceSizeChanged); - surface.SurfaceMessage += new SurfaceMessageEventHandler(SurfaceMessageReceived); - surface.FieldAggregator.FieldChanged += new FieldChangedEventHandler(FieldAggregatorFieldChanged); - SurfaceSizeChanged(this.Surface, null); + 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) { - this.Text = surface.CaptureDetails.Title + " - " + Language.GetString(LangKey.editor_title); + Text = surface.CaptureDetails.Title + " - " + Language.GetString(LangKey.editor_title); } - WindowDetails.ToForeground(this.Handle); + WindowDetails.ToForeground(Handle); } private void updateUI() { - this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); + Icon = GreenshotResources.getGreenshotIcon(); // Disable access to the settings, for feature #3521446 preferencesToolStripMenuItem.Visible = !coreConfiguration.DisableSettings; @@ -171,18 +170,18 @@ namespace Greenshot { // a smaller size than the initial panel size (as set by the forms designer) panel1.Height = 10; - this.fontFamilyComboBox.PropertyChanged += new PropertyChangedEventHandler(FontPropertyChanged); + fontFamilyComboBox.PropertyChanged += FontPropertyChanged; obfuscateModeButton.DropDownItemClicked += FilterPresetDropDownItemClicked; highlightModeButton.DropDownItemClicked += FilterPresetDropDownItemClicked; - toolbarButtons = new GreenshotPlugin.Controls.GreenshotToolStripButton[] { btnCursor, btnRect, btnEllipse, btnText, btnLine, btnArrow, btnFreehand, btnHighlight, btnObfuscate, btnCrop }; + toolbarButtons = new[] { btnCursor, btnRect, btnEllipse, btnText, btnLine, btnArrow, btnFreehand, btnHighlight, btnObfuscate, btnCrop }; //toolbarDropDownButtons = new ToolStripDropDownButton[]{btnBlur, btnPixeliate, btnTextHighlighter, btnAreaHighlighter, btnMagnifier}; pluginToolStripMenuItem.Visible = pluginToolStripMenuItem.DropDownItems.Count > 0; // Workaround: for the MouseWheel event which doesn't get to the panel - this.MouseWheel += new MouseEventHandler( PanelMouseWheel); + MouseWheel += PanelMouseWheel; ApplyLanguage(); } @@ -191,7 +190,7 @@ namespace Greenshot { /// Get all the destinations and display them in the file menu and the buttons /// void AddDestinations() { - this.Invoke((MethodInvoker)delegate { + Invoke((MethodInvoker)delegate { // Create export buttons foreach(IDestination destination in DestinationHelper.GetAllDestinations()) { if (destination.Priority <= 2) { @@ -217,8 +216,8 @@ namespace Greenshot { if (toolstripDestination.isDynamic) { ToolStripSplitButton destinationButton = new ToolStripSplitButton(); //ToolStripDropDownButton destinationButton = new ToolStripDropDownButton(); - destinationButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - destinationButton.Size = new System.Drawing.Size(23, 22); + destinationButton.DisplayStyle = ToolStripItemDisplayStyle.Image; + destinationButton.Size = new Size(23, 22); destinationButton.Text = toolstripDestination.Description; destinationButton.Image = toolstripDestination.DisplayIcon; @@ -261,8 +260,8 @@ namespace Greenshot { } else { ToolStripButton destinationButton = new ToolStripButton(); toolStrip1.Items.Insert(toolStrip1.Items.IndexOf(toolStripSeparator16), destinationButton); - destinationButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - destinationButton.Size = new System.Drawing.Size(23, 22); + destinationButton.DisplayStyle = ToolStripItemDisplayStyle.Image; + destinationButton.Size = new Size(23, 22); destinationButton.Text = toolstripDestination.Description; destinationButton.Image = toolstripDestination.DisplayIcon; destinationButton.Click += delegate(object sender, EventArgs e) { @@ -287,7 +286,7 @@ namespace Greenshot { } void FileMenuDropDownOpening(object sender, EventArgs eventArgs) { - ClearItems(this.fileStripMenuItem.DropDownItems); + ClearItems(fileStripMenuItem.DropDownItems); // Add the destinations foreach(IDestination destination in DestinationHelper.GetAllDestinations()) { @@ -298,15 +297,15 @@ namespace Greenshot { continue; } - ToolStripMenuItem item = destination.GetMenuItem(true, null, new EventHandler(DestinationToolStripMenuItemClick)); + ToolStripMenuItem item = destination.GetMenuItem(true, null, DestinationToolStripMenuItemClick); if (item != null) { item.ShortcutKeys = destination.EditorShortcutKeys; fileStripMenuItem.DropDownItems.Add(item); } } // add the elements after the destinations - this.fileStripMenuItem.DropDownItems.Add(this.toolStripSeparator9); - this.fileStripMenuItem.DropDownItems.Add(this.closeToolStripMenuItem); + fileStripMenuItem.DropDownItems.Add(toolStripSeparator9); + fileStripMenuItem.DropDownItems.Add(closeToolStripMenuItem); } /// @@ -323,7 +322,7 @@ namespace Greenshot { // Put the event message on the status label and attach the context menu updateStatusLabel(dateTime + " - " + eventArgs.Message, fileSavedStatusContextMenu); // Change title - this.Text = eventArgs.Surface.LastSaveFullPath + " - " + Language.GetString(LangKey.editor_title); + Text = eventArgs.Surface.LastSaveFullPath + " - " + Language.GetString(LangKey.editor_title); break; case SurfaceMessageTyp.Error: case SurfaceMessageTyp.Info: @@ -342,16 +341,16 @@ namespace Greenshot { private void SurfaceSizeChanged(object sender, EventArgs e) { if (editorConfiguration.MatchSizeToCapture) { // Set editor's initial size to the size of the surface plus the size of the chrome - Size imageSize = this.Surface.Image.Size; - Size currentFormSize = this.Size; - Size currentImageClientSize = this.panel1.ClientSize; + 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); - this.Size = new Size(newWidth, newHeight); + Size = new Size(newWidth, newHeight); } - dimensionsLabel.Text = this.Surface.Image.Width + "x" + this.Surface.Image.Height; + dimensionsLabel.Text = Surface.Image.Width + "x" + Surface.Image.Height; ImageEditorFormResize(sender, new EventArgs()); } @@ -375,7 +374,7 @@ namespace Greenshot { return; } updateStatusLabel(Language.GetFormattedString(LangKey.editor_imagesaved, fullpath), fileSavedStatusContextMenu); - this.Text = Path.GetFileName(fullpath) + " - " + Language.GetString(LangKey.editor_title); + Text = Path.GetFileName(fullpath) + " - " + Language.GetString(LangKey.editor_title); } void surface_DrawingModeChanged(object source, SurfaceDrawingModeEventArgs eventArgs) { @@ -438,26 +437,26 @@ namespace Greenshot { #region filesystem options void BtnSaveClick(object sender, EventArgs e) { - string destinationDesignation = Destinations.FileDestination.DESIGNATION; + string destinationDesignation = FileDestination.DESIGNATION; if (surface.LastSaveFullPath == null) { - destinationDesignation = Destinations.FileWithDialogDestination.DESIGNATION; + destinationDesignation = FileWithDialogDestination.DESIGNATION; } DestinationHelper.ExportCapture(true, destinationDesignation, surface, surface.CaptureDetails); } void BtnClipboardClick(object sender, EventArgs e) { - DestinationHelper.ExportCapture(true, Destinations.ClipboardDestination.DESIGNATION, surface, surface.CaptureDetails); + DestinationHelper.ExportCapture(true, ClipboardDestination.DESIGNATION, surface, surface.CaptureDetails); } void BtnPrintClick(object sender, EventArgs e) { // The BeginInvoke is a solution for the printdialog not having focus - this.BeginInvoke((MethodInvoker) delegate { - DestinationHelper.ExportCapture(true, Destinations.PrinterDestination.DESIGNATION, surface, surface.CaptureDetails); + BeginInvoke((MethodInvoker) delegate { + DestinationHelper.ExportCapture(true, PrinterDestination.DESIGNATION, surface, surface.CaptureDetails); }); } - void CloseToolStripMenuItemClick(object sender, System.EventArgs e) { - this.Close(); + void CloseToolStripMenuItemClick(object sender, EventArgs e) { + Close(); } #endregion @@ -525,23 +524,23 @@ namespace Greenshot { } } - void AddRectangleToolStripMenuItemClick(object sender, System.EventArgs e) { + void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) { BtnRectClick(sender, e); } - void DrawFreehandToolStripMenuItemClick(object sender, System.EventArgs e) { + void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) { BtnFreehandClick(sender, e); } - void AddEllipseToolStripMenuItemClick(object sender, System.EventArgs e) { + void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) { BtnEllipseClick(sender, e); } - void AddTextBoxToolStripMenuItemClick(object sender, System.EventArgs e) { + void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) { BtnTextClick(sender, e); } - void DrawLineToolStripMenuItemClick(object sender, System.EventArgs e) { + void DrawLineToolStripMenuItemClick(object sender, EventArgs e) { BtnLineClick(sender, e); } @@ -557,7 +556,7 @@ namespace Greenshot { BtnObfuscateClick(sender, e); } - void RemoveObjectToolStripMenuItemClick(object sender, System.EventArgs e) { + void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) { surface.RemoveSelectedElements(); } @@ -567,52 +566,52 @@ namespace Greenshot { #endregion #region copy&paste options - void CutToolStripMenuItemClick(object sender, System.EventArgs e) { + void CutToolStripMenuItemClick(object sender, EventArgs e) { surface.CutSelectedElements(); updateClipboardSurfaceDependencies(); } - void BtnCutClick(object sender, System.EventArgs e) { + void BtnCutClick(object sender, EventArgs e) { CutToolStripMenuItemClick(sender, e); } - void CopyToolStripMenuItemClick(object sender, System.EventArgs e) { + void CopyToolStripMenuItemClick(object sender, EventArgs e) { surface.CopySelectedElements(); updateClipboardSurfaceDependencies(); } - void BtnCopyClick(object sender, System.EventArgs e) { + void BtnCopyClick(object sender, EventArgs e) { CopyToolStripMenuItemClick(sender, e); } - void PasteToolStripMenuItemClick(object sender, System.EventArgs e) { + void PasteToolStripMenuItemClick(object sender, EventArgs e) { surface.PasteElementFromClipboard(); updateClipboardSurfaceDependencies(); } - void BtnPasteClick(object sender, System.EventArgs e) { + void BtnPasteClick(object sender, EventArgs e) { PasteToolStripMenuItemClick(sender, e); } - void UndoToolStripMenuItemClick(object sender, System.EventArgs e) { + void UndoToolStripMenuItemClick(object sender, EventArgs e) { surface.Undo(); updateUndoRedoSurfaceDependencies(); } - void BtnUndoClick(object sender, System.EventArgs e) { + void BtnUndoClick(object sender, EventArgs e) { UndoToolStripMenuItemClick(sender, e); } - void RedoToolStripMenuItemClick(object sender, System.EventArgs e) { + void RedoToolStripMenuItemClick(object sender, EventArgs e) { surface.Redo(); updateUndoRedoSurfaceDependencies(); } - void BtnRedoClick(object sender, System.EventArgs e) { + void BtnRedoClick(object sender, EventArgs e) { RedoToolStripMenuItemClick(sender, e); } - void DuplicateToolStripMenuItemClick(object sender, System.EventArgs e) { + void DuplicateToolStripMenuItemClick(object sender, EventArgs e) { surface.DuplicateSelectedElements(); updateClipboardSurfaceDependencies(); } @@ -639,23 +638,23 @@ namespace Greenshot { #endregion #region help - void HelpToolStripMenuItem1Click(object sender, System.EventArgs e) { + void HelpToolStripMenuItem1Click(object sender, EventArgs e) { HelpFileLoader.LoadHelp(); } - void AboutToolStripMenuItemClick(object sender, System.EventArgs e) { + void AboutToolStripMenuItemClick(object sender, EventArgs e) { MainForm.Instance.ShowAbout(); } - void PreferencesToolStripMenuItemClick(object sender, System.EventArgs e) { + void PreferencesToolStripMenuItemClick(object sender, EventArgs e) { MainForm.Instance.ShowSetting(); } - void BtnSettingsClick(object sender, System.EventArgs e) { + void BtnSettingsClick(object sender, EventArgs e) { PreferencesToolStripMenuItemClick(sender, e); } - void BtnHelpClick(object sender, System.EventArgs e) { + void BtnHelpClick(object sender, EventArgs e) { HelpToolStripMenuItem1Click(sender, e); } #endregion @@ -669,7 +668,7 @@ namespace Greenshot { void ImageEditorFormFormClosing(object sender, FormClosingEventArgs e) { if (surface.Modified && !editorConfiguration.SuppressSaveDialogAtClose) { // Make sure the editor is visible - WindowDetails.ToForeground(this.Handle); + WindowDetails.ToForeground(Handle); MessageBoxButtons buttons = MessageBoxButtons.YesNoCancel; // Dissallow "CANCEL" if the application needs to shutdown @@ -691,7 +690,7 @@ namespace Greenshot { } } // persist our geometry string. - editorConfiguration.SetEditorPlacement(new WindowDetails(this.Handle).WindowPlacement); + editorConfiguration.SetEditorPlacement(new WindowDetails(Handle).WindowPlacement); IniConfig.Save(); // remove from the editor list @@ -699,7 +698,7 @@ namespace Greenshot { surface.Dispose(); - System.GC.Collect(); + GC.Collect(); } void ImageEditorFormKeyDown(object sender, KeyEventArgs e) { @@ -829,8 +828,8 @@ namespace Greenshot { return; } bool canUndo = surface.CanUndo; - this.btnUndo.Enabled = canUndo; - this.undoToolStripMenuItem.Enabled = canUndo; + btnUndo.Enabled = canUndo; + undoToolStripMenuItem.Enabled = canUndo; string undoAction = ""; if (canUndo) { if (surface.UndoActionLanguageKey != LangKey.none) { @@ -838,12 +837,12 @@ namespace Greenshot { } } string undoText = Language.GetFormattedString(LangKey.editor_undo, undoAction); - this.btnUndo.Text = undoText; - this.undoToolStripMenuItem.Text = undoText; + btnUndo.Text = undoText; + undoToolStripMenuItem.Text = undoText; bool canRedo = surface.CanRedo; - this.btnRedo.Enabled = canRedo; - this.redoToolStripMenuItem.Enabled = canRedo; + btnRedo.Enabled = canRedo; + redoToolStripMenuItem.Enabled = canRedo; string redoAction = ""; if (canRedo) { if (surface.RedoActionLanguageKey != LangKey.none) { @@ -851,8 +850,8 @@ namespace Greenshot { } } string redoText = Language.GetFormattedString(LangKey.editor_redo, redoAction); - this.btnRedo.Text = redoText; - this.redoToolStripMenuItem.Text = redoText; + btnRedo.Text = redoText; + redoToolStripMenuItem.Text = redoText; } @@ -865,20 +864,20 @@ namespace Greenshot { bool actionAllowedForSelection = hasItems && !controlsDisabledDueToConfirmable; // buttons - this.btnCut.Enabled = actionAllowedForSelection; - this.btnCopy.Enabled = actionAllowedForSelection; - this.btnDelete.Enabled = actionAllowedForSelection; + btnCut.Enabled = actionAllowedForSelection; + btnCopy.Enabled = actionAllowedForSelection; + btnDelete.Enabled = actionAllowedForSelection; // menus - this.removeObjectToolStripMenuItem.Enabled = actionAllowedForSelection; - this.copyToolStripMenuItem.Enabled = actionAllowedForSelection; - this.cutToolStripMenuItem.Enabled = actionAllowedForSelection; - this.duplicateToolStripMenuItem.Enabled = actionAllowedForSelection; + removeObjectToolStripMenuItem.Enabled = actionAllowedForSelection; + copyToolStripMenuItem.Enabled = actionAllowedForSelection; + cutToolStripMenuItem.Enabled = actionAllowedForSelection; + duplicateToolStripMenuItem.Enabled = actionAllowedForSelection; // check dependencies for the Clipboard bool hasClipboard = ClipboardHelper.ContainsFormat(SUPPORTED_CLIPBOARD_FORMATS) || ClipboardHelper.ContainsImage(); - this.btnPaste.Enabled = hasClipboard && !controlsDisabledDueToConfirmable; - this.pasteToolStripMenuItem.Enabled = hasClipboard && !controlsDisabledDueToConfirmable; + btnPaste.Enabled = hasClipboard && !controlsDisabledDueToConfirmable; + pasteToolStripMenuItem.Enabled = hasClipboard && !controlsDisabledDueToConfirmable; } #endregion @@ -1012,12 +1011,12 @@ namespace Greenshot { bool actionAllowedForSelection = surface.HasSelectedElements && !controlsDisabledDueToConfirmable; bool push = actionAllowedForSelection && surface.CanPushSelectionDown(); bool pull = actionAllowedForSelection && surface.CanPullSelectionUp(); - this.arrangeToolStripMenuItem.Enabled = (push || pull); - if (this.arrangeToolStripMenuItem.Enabled) { - this.upToTopToolStripMenuItem.Enabled = pull; - this.upOneLevelToolStripMenuItem.Enabled = pull; - this.downToBottomToolStripMenuItem.Enabled = push; - this.downOneLevelToolStripMenuItem.Enabled = push; + arrangeToolStripMenuItem.Enabled = (push || pull); + if (arrangeToolStripMenuItem.Enabled) { + upToTopToolStripMenuItem.Enabled = pull; + upOneLevelToolStripMenuItem.Enabled = pull; + downToBottomToolStripMenuItem.Enabled = push; + downOneLevelToolStripMenuItem.Enabled = push; } // finally show/hide field controls depending on the fields of selected elements @@ -1074,14 +1073,14 @@ namespace Greenshot { originalBoldCheckState = fontBoldButton.Checked; } - void FontItalicButtonClick(object sender, System.EventArgs e) { + void FontItalicButtonClick(object sender, EventArgs e) { originalItalicCheckState = fontItalicButton.Checked; } - void ToolBarFocusableElementGotFocus(object sender, System.EventArgs e) { + void ToolBarFocusableElementGotFocus(object sender, EventArgs e) { surface.KeysLocked = true; } - void ToolBarFocusableElementLostFocus(object sender, System.EventArgs e) { + void ToolBarFocusableElementLostFocus(object sender, EventArgs e) { surface.KeysLocked = false; } @@ -1131,7 +1130,7 @@ namespace Greenshot { protected void FilterPresetDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { refreshFieldControls(); - this.Invalidate(true); + Invalidate(true); } void SelectAllToolStripMenuItemClick(object sender, EventArgs e) { @@ -1159,15 +1158,15 @@ namespace Greenshot { try { WindowDetails windowToCapture = (WindowDetails)clickedItem.Tag; ICapture capture = new Capture(); - using (Graphics graphics = Graphics.FromHwnd(this.Handle)) { + using (Graphics graphics = Graphics.FromHwnd(Handle)) { capture.CaptureDetails.DpiX = graphics.DpiY; capture.CaptureDetails.DpiY = graphics.DpiY; } windowToCapture = CaptureHelper.SelectCaptureWindow(windowToCapture); if (windowToCapture != null) { capture = CaptureHelper.CaptureWindow(windowToCapture, capture, coreConfiguration.WindowCaptureMode); - this.Activate(); - WindowDetails.ToForeground(this.Handle); + Activate(); + WindowDetails.ToForeground(Handle); if (capture!= null && capture.Image != null) { surface.AddImageContainer((Bitmap)capture.Image, 100, 100); } @@ -1263,12 +1262,12 @@ namespace Greenshot { } private void ImageEditorFormResize(object sender, EventArgs e) { - if (this.Surface == null || this.Surface.Image == null || this.panel1 == null) { + if (Surface == null || Surface.Image == null || panel1 == null) { return; } - Size imageSize = this.Surface.Image.Size; - Size currentClientSize = this.panel1.ClientSize; - var canvas = this.Surface as Control; + Size imageSize = Surface.Image.Size; + Size currentClientSize = panel1.ClientSize; + var canvas = Surface as Control; Panel panel = (Panel)canvas.Parent; if (panel == null) { return; diff --git a/Greenshot/Forms/LanguageDialog.cs b/Greenshot/Forms/LanguageDialog.cs index c04d5450d..8b6dfeeb8 100644 --- a/Greenshot/Forms/LanguageDialog.cs +++ b/Greenshot/Forms/LanguageDialog.cs @@ -21,16 +21,15 @@ using System; using System.Threading; using System.Windows.Forms; - -using Greenshot.Configuration; using GreenshotPlugin.Core; +using log4net; namespace Greenshot.Forms { /// /// Description of LanguageDialog. /// public partial class LanguageDialog : Form { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(LanguageDialog)); + private static ILog LOG = LogManager.GetLogger(typeof(LanguageDialog)); private static LanguageDialog uniqueInstance; private bool properOkPressed = false; @@ -39,9 +38,9 @@ namespace Greenshot.Forms { // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); - this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); - this.Load += FormLoad; - this.FormClosing += PreventFormClose; + Icon = GreenshotResources.getGreenshotIcon(); + Load += FormLoad; + FormClosing += PreventFormClose; } private void PreventFormClose(object sender, FormClosingEventArgs e) { @@ -56,27 +55,27 @@ namespace Greenshot.Forms { protected void FormLoad(object sender, EventArgs e) { // Initialize the Language ComboBox - this.comboBoxLanguage.DisplayMember = "Description"; - this.comboBoxLanguage.ValueMember = "Ietf"; + comboBoxLanguage.DisplayMember = "Description"; + comboBoxLanguage.ValueMember = "Ietf"; // Set datasource last to prevent problems // See: http://www.codeproject.com/KB/database/scomlistcontrolbinding.aspx?fid=111644 - this.comboBoxLanguage.DataSource = Language.SupportedLanguages; + comboBoxLanguage.DataSource = Language.SupportedLanguages; if (Language.CurrentLanguage != null) { LOG.DebugFormat("Selecting {0}", Language.CurrentLanguage); - this.comboBoxLanguage.SelectedValue = Language.CurrentLanguage; + comboBoxLanguage.SelectedValue = Language.CurrentLanguage; } else { - this.comboBoxLanguage.SelectedValue = Thread.CurrentThread.CurrentUICulture.Name; + comboBoxLanguage.SelectedValue = Thread.CurrentThread.CurrentUICulture.Name; } // Close again when there is only one language, this shows the form briefly! // But the use-case is not so interesting, only happens once, to invest a lot of time here. if (Language.SupportedLanguages.Count == 1) { - this.comboBoxLanguage.SelectedValue = Language.SupportedLanguages[0].Ietf; + comboBoxLanguage.SelectedValue = Language.SupportedLanguages[0].Ietf; Language.CurrentLanguage = SelectedLanguage; properOkPressed = true; - this.Close(); + Close(); } } @@ -84,7 +83,7 @@ namespace Greenshot.Forms { properOkPressed = true; // Fix for Bug #3431100 Language.CurrentLanguage = SelectedLanguage; - this.Close(); + Close(); } public static LanguageDialog GetInstance() { diff --git a/Greenshot/Forms/MainForm.Designer.cs b/Greenshot/Forms/MainForm.Designer.cs index 05d140691..448425932 100644 --- a/Greenshot/Forms/MainForm.Designer.cs +++ b/Greenshot/Forms/MainForm.Designer.cs @@ -34,8 +34,8 @@ namespace Greenshot { if (components != null) { components.Dispose(); } - if (copyData != null) { - copyData.Dispose(); + if (_copyData != null) { + _copyData.Dispose(); } } base.Dispose(disposing); diff --git a/Greenshot/Forms/MainForm.cs b/Greenshot/Forms/MainForm.cs index ae70a78aa..fdc7cbf65 100644 --- a/Greenshot/Forms/MainForm.cs +++ b/Greenshot/Forms/MainForm.cs @@ -20,6 +20,7 @@ */ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; @@ -41,15 +42,17 @@ using GreenshotPlugin.Controls; using GreenshotPlugin.Core; using Greenshot.IniFile; using Greenshot.Destinations; +using log4net; +using Timer = System.Timers.Timer; namespace Greenshot { /// /// Description of MainForm. /// public partial class MainForm : BaseForm { - private static log4net.ILog LOG = null; - private static Mutex applicationMutex = null; - private static CoreConfiguration conf; + private static ILog LOG; + private static Mutex _applicationMutex; + private static CoreConfiguration _conf; public static string LogFileLocation = null; public static void Start(string[] args) { @@ -62,10 +65,10 @@ namespace Greenshot { // Init Log4NET LogFileLocation = LogHelper.InitializeLog4NET(); // Get logger - LOG = log4net.LogManager.GetLogger(typeof(MainForm)); + LOG = LogManager.GetLogger(typeof(MainForm)); - Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); + Application.ThreadException += Application_ThreadException; + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Initialize the IniConfig IniConfig.Init(); @@ -77,7 +80,7 @@ namespace Greenshot { AppConfig.UpgradeToIni(); // Read configuration - conf = IniConfig.GetIniSection(); + _conf = IniConfig.GetIniSection(); try { // Fix for Bug 2495900, Multi-user Environment // check whether there's an local instance running already @@ -91,16 +94,16 @@ namespace Greenshot { mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny)); - bool created = false; + bool created; // 1) Create Mutex - applicationMutex = new Mutex(false, @"Local\F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", out created, mutexsecurity); + _applicationMutex = new Mutex(false, @"Local\F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", out created, mutexsecurity); // 2) Get the right to it, this returns false if it's already locked - if (!applicationMutex.WaitOne(0, false)) { + if (!_applicationMutex.WaitOne(0, false)) { LOG.Debug("Greenshot seems already to be running!"); isAlreadyRunning = true; // Clean up - applicationMutex.Close(); - applicationMutex = null; + _applicationMutex.Close(); + _applicationMutex = null; } } catch (AbandonedMutexException e) { // Another Greenshot instance didn't cleanup correctly! @@ -119,7 +122,7 @@ namespace Greenshot { for(int argumentNr = 0; argumentNr < args.Length; argumentNr++) { argumentString.Append("[").Append(args[argumentNr]).Append("] "); } - LOG.Debug("Greenshot arguments: " + argumentString.ToString()); + LOG.Debug("Greenshot arguments: " + argumentString); } for(int argumentNr = 0; argumentNr < args.Length; argumentNr++) { @@ -201,7 +204,7 @@ namespace Greenshot { // Language if (argument.ToLower().Equals("/language")) { - conf.Language = args[++argumentNr]; + _conf.Language = args[++argumentNr]; IniConfig.Save(); continue; } @@ -243,9 +246,9 @@ namespace Greenshot { } } if (!matchedThisProcess) { - instanceInfo.Append(index++ + ": ").AppendLine(Kernel32.GetProcessPath(new IntPtr(Process.GetCurrentProcess().Id))); + instanceInfo.Append(index + ": ").AppendLine(Kernel32.GetProcessPath(new IntPtr(Process.GetCurrentProcess().Id))); } - MessageBox.Show(Language.GetString(LangKey.error_multipleinstances) + "\r\n" + instanceInfo.ToString(), Language.GetString(LangKey.error)); + MessageBox.Show(Language.GetString(LangKey.error_multipleinstances) + "\r\n" + instanceInfo, Language.GetString(LangKey.error)); } FreeMutex(); Application.Exit(); @@ -257,25 +260,25 @@ namespace Greenshot { Application.SetCompatibleTextRenderingDefault(false); // if language is not set, show language dialog - if(string.IsNullOrEmpty(conf.Language)) { + if(string.IsNullOrEmpty(_conf.Language)) { LanguageDialog languageDialog = LanguageDialog.GetInstance(); languageDialog.ShowDialog(); - conf.Language = languageDialog.SelectedLanguage; + _conf.Language = languageDialog.SelectedLanguage; IniConfig.Save(); } // Check if it's the first time launch? - if(conf.IsFirstLaunch) { - conf.IsFirstLaunch = false; + if(_conf.IsFirstLaunch) { + _conf.IsFirstLaunch = false; IniConfig.Save(); transport.AddCommand(CommandEnum.FirstLaunch); } - MainForm mainForm = new MainForm(transport); + new MainForm(transport); Application.Run(); } catch(Exception ex) { LOG.Error("Exception in startup.", ex); - Application_ThreadException(MainForm.ActiveForm, new ThreadExceptionEventArgs(ex)); + Application_ThreadException(ActiveForm, new ThreadExceptionEventArgs(ex)); } } @@ -292,36 +295,33 @@ namespace Greenshot { private static void FreeMutex() { // Remove the application mutex - if (applicationMutex != null) { + if (_applicationMutex != null) { try { - applicationMutex.ReleaseMutex(); - applicationMutex = null; + _applicationMutex.ReleaseMutex(); + _applicationMutex = null; } catch (Exception ex) { LOG.Error("Error releasing Mutex!", ex); } } } - private static MainForm instance = null; + private static MainForm _instance; public static MainForm Instance { get { - return instance; + return _instance; } } - private ToolTip tooltip; - private CopyData copyData = null; + private readonly CopyData _copyData; // Thumbnail preview - private ThumbnailForm thumbnailForm = null; - private IntPtr thumbnailHandle = IntPtr.Zero; - private Rectangle parentMenuBounds = Rectangle.Empty; + private ThumbnailForm _thumbnailForm; // Make sure we have only one settings form - private SettingsForm settingsForm = null; + private SettingsForm _settingsForm; // Make sure we have only one about form - private AboutForm aboutForm = null; + private AboutForm _aboutForm; // Timer for the double click test - private System.Timers.Timer doubleClickTimer = new System.Timers.Timer(); + private readonly Timer _doubleClickTimer = new Timer(); public NotifyIcon NotifyIcon { get { @@ -330,7 +330,7 @@ namespace Greenshot { } public MainForm(CopyDataTransport dataTransport) { - instance = this; + _instance = this; // // The InitializeComponent() call is required for Windows Forms designer support. @@ -342,17 +342,17 @@ namespace Greenshot { ex.Data.Add("more information here", "http://support.microsoft.com/kb/943140"); throw; } - this.notifyIcon.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); - this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); + notifyIcon.Icon = GreenshotResources.getGreenshotIcon(); + Icon = GreenshotResources.getGreenshotIcon(); // Disable access to the settings, for feature #3521446 - contextmenu_settings.Visible = !conf.DisableSettings; + contextmenu_settings.Visible = !_conf.DisableSettings; // Make sure all hotkeys pass this window! - HotkeyControl.RegisterHotkeyHWND(this.Handle); + HotkeyControl.RegisterHotkeyHWND(Handle); RegisterHotkeys(); - tooltip = new ToolTip(); + new ToolTip(); UpdateUI(); @@ -365,17 +365,17 @@ namespace Greenshot { PluginHelper.Instance.LoadPlugins(); // Check destinations, remove all that don't exist - foreach(string destination in conf.OutputDestinations.ToArray()) { + foreach(string destination in _conf.OutputDestinations.ToArray()) { if (DestinationHelper.GetDestination(destination) == null) { - conf.OutputDestinations.Remove(destination); + _conf.OutputDestinations.Remove(destination); } } // we should have at least one! - if (conf.OutputDestinations.Count == 0) { - conf.OutputDestinations.Add(Destinations.EditorDestination.DESIGNATION); + if (_conf.OutputDestinations.Count == 0) { + _conf.OutputDestinations.Add(EditorDestination.DESIGNATION); } - if (conf.DisableQuickSettings) { + if (_conf.DisableQuickSettings) { contextmenu_quicksettings.Visible = false; } else { // Do after all plugins & finding the destination, otherwise they are missing! @@ -385,20 +385,20 @@ namespace Greenshot { // Set the Greenshot icon visibility depending on the configuration. (Added for feature #3521446) // Setting it to true this late prevents Problems with the context menu - notifyIcon.Visible = !conf.HideTrayicon; + notifyIcon.Visible = !_conf.HideTrayicon; // Make sure we never capture the mainform - WindowDetails.RegisterIgnoreHandle(this.Handle); + WindowDetails.RegisterIgnoreHandle(Handle); // Create a new instance of the class: copyData = new CopyData(); - copyData = new CopyData(); + _copyData = new CopyData(); // Assign the handle: - copyData.AssignHandle(this.Handle); + _copyData.AssignHandle(Handle); // Create the channel to send on: - copyData.Channels.Add("Greenshot"); + _copyData.Channels.Add("Greenshot"); // Hook up received event: - copyData.CopyDataReceived += new CopyDataReceivedEventHandler(CopyDataDataReceived); + _copyData.CopyDataReceived += CopyDataDataReceived; if (dataTransport != null) { HandleDataTransport(dataTransport); @@ -409,10 +409,10 @@ namespace Greenshot { /// DataReceivedEventHandler /// /// - /// + /// private void CopyDataDataReceived(object sender, CopyDataReceivedEventArgs copyDataReceivedEventArgs) { // Cast the data to the type of object we sent: - CopyDataTransport dataTransport = (CopyDataTransport)copyDataReceivedEventArgs.Data; + var dataTransport = (CopyDataTransport)copyDataReceivedEventArgs.Data; HandleDataTransport(dataTransport); } @@ -430,26 +430,26 @@ namespace Greenshot { try { EventHandler balloonTipClickedHandler = null; EventHandler balloonTipClosedHandler = null; - balloonTipClosedHandler = delegate(object sender, EventArgs e) { + balloonTipClosedHandler = delegate { notifyIcon.BalloonTipClicked -= balloonTipClickedHandler; notifyIcon.BalloonTipClosed -= balloonTipClosedHandler; }; - balloonTipClickedHandler = delegate(object sender, EventArgs e) { + balloonTipClickedHandler = delegate { ShowSetting(); notifyIcon.BalloonTipClicked -= balloonTipClickedHandler; notifyIcon.BalloonTipClosed -= balloonTipClosedHandler; }; notifyIcon.BalloonTipClicked += balloonTipClickedHandler; notifyIcon.BalloonTipClosed += balloonTipClosedHandler; - notifyIcon.ShowBalloonTip(2000, "Greenshot", Language.GetFormattedString(LangKey.tooltip_firststart, HotkeyControl.GetLocalizedHotkeyStringFromString(conf.RegionHotkey)), ToolTipIcon.Info); + notifyIcon.ShowBalloonTip(2000, "Greenshot", Language.GetFormattedString(LangKey.tooltip_firststart, HotkeyControl.GetLocalizedHotkeyStringFromString(_conf.RegionHotkey)), ToolTipIcon.Info); } catch {} break; case CommandEnum.ReloadConfig: LOG.Info("Reload requested"); try { IniConfig.Reload(); - this.Invoke((MethodInvoker)delegate { + Invoke((MethodInvoker)delegate { // Even update language when needed UpdateUI(); // Update the hotkey @@ -518,13 +518,13 @@ namespace Greenshot { } private static bool RegisterWrapper(StringBuilder failedKeys, string functionName, string configurationKey, HotKeyHandler handler, bool ignoreFailedRegistration) { - IniValue hotkeyValue = conf.Values[configurationKey]; + IniValue hotkeyValue = _conf.Values[configurationKey]; try { bool success = RegisterHotkey(failedKeys, functionName, hotkeyValue.Value.ToString(), handler); if (!success && ignoreFailedRegistration) { LOG.DebugFormat("Ignoring failed hotkey registration, resetting to 'None'.", functionName, hotkeyValue); - conf.Values[configurationKey].Value = Keys.None.ToString(); - conf.IsDirty = true; + _conf.Values[configurationKey].Value = Keys.None.ToString(); + _conf.IsDirty = true; } return success; } catch (Exception ex) { @@ -551,26 +551,26 @@ namespace Greenshot { /// if true, a failed hotkey registration will not be reported to the user - the hotkey will simply not be registered /// Whether the hotkeys could be registered to the users content. This also applies if conflicts arise and the user decides to ignore these (i.e. not to register the conflicting hotkey). private static bool RegisterHotkeys(bool ignoreFailedRegistration) { - if (instance == null) { + if (_instance == null) { return false; } bool success = true; StringBuilder failedKeys = new StringBuilder(); - if (!RegisterWrapper(failedKeys, "CaptureRegion", "RegionHotkey", new HotKeyHandler(instance.CaptureRegion), ignoreFailedRegistration)) { + if (!RegisterWrapper(failedKeys, "CaptureRegion", "RegionHotkey", _instance.CaptureRegion, ignoreFailedRegistration)) { success = false; } - if (!RegisterWrapper(failedKeys, "CaptureWindow", "WindowHotkey", new HotKeyHandler(instance.CaptureWindow), ignoreFailedRegistration)) { + if (!RegisterWrapper(failedKeys, "CaptureWindow", "WindowHotkey", _instance.CaptureWindow, ignoreFailedRegistration)) { success = false; } - if (!RegisterWrapper(failedKeys, "CaptureFullScreen", "FullscreenHotkey", new HotKeyHandler(instance.CaptureFullScreen), ignoreFailedRegistration)) { + if (!RegisterWrapper(failedKeys, "CaptureFullScreen", "FullscreenHotkey", _instance.CaptureFullScreen, ignoreFailedRegistration)) { success = false; } - if (!RegisterWrapper(failedKeys, "CaptureLastRegion", "LastregionHotkey", new HotKeyHandler(instance.CaptureLastRegion), ignoreFailedRegistration)) { + if (!RegisterWrapper(failedKeys, "CaptureLastRegion", "LastregionHotkey", _instance.CaptureLastRegion, ignoreFailedRegistration)) { success = false; } - if (conf.IECapture) { - if (!RegisterWrapper(failedKeys, "CaptureIE", "IEHotkey", new HotKeyHandler(instance.CaptureIE), ignoreFailedRegistration)) { + if (_conf.IECapture) { + if (!RegisterWrapper(failedKeys, "CaptureIE", "IEHotkey", _instance.CaptureIE, ignoreFailedRegistration)) { success = false; } } @@ -580,7 +580,7 @@ namespace Greenshot { success = HandleFailedHotkeyRegistration(failedKeys.ToString()); } else { // if failures have been ignored, the config has probably been updated - if (conf.IsDirty) IniConfig.Save(); + if (_conf.IsDirty) IniConfig.Save(); } } return success || ignoreFailedRegistration; @@ -596,7 +596,7 @@ namespace Greenshot { /// private static bool HandleFailedHotkeyRegistration(string failedKeys) { bool success = false; - DialogResult dr = MessageBox.Show(MainForm.Instance, Language.GetFormattedString(LangKey.warning_hotkeys, failedKeys), Language.GetString(LangKey.warning), MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation); + DialogResult dr = MessageBox.Show(Instance, Language.GetFormattedString(LangKey.warning_hotkeys, failedKeys), Language.GetString(LangKey.warning), MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation); if (dr == DialogResult.Retry) { LOG.DebugFormat("Re-trying to register hotkeys"); HotkeyControl.UnregisterHotkeys(); @@ -615,18 +615,18 @@ namespace Greenshot { ApplyLanguage(); // Show hotkeys in Contextmenu - this.contextmenu_capturearea.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(conf.RegionHotkey); - this.contextmenu_capturelastregion.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(conf.LastregionHotkey); - this.contextmenu_capturewindow.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(conf.WindowHotkey); - this.contextmenu_capturefullscreen.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(conf.FullscreenHotkey); - this.contextmenu_captureie.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(conf.IEHotkey); + contextmenu_capturearea.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(_conf.RegionHotkey); + contextmenu_capturelastregion.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(_conf.LastregionHotkey); + contextmenu_capturewindow.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(_conf.WindowHotkey); + contextmenu_capturefullscreen.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(_conf.FullscreenHotkey); + contextmenu_captureie.ShortcutKeyDisplayString = HotkeyControl.GetLocalizedHotkeyStringFromString(_conf.IEHotkey); } #region mainform events void MainFormFormClosing(object sender, FormClosingEventArgs e) { LOG.DebugFormat("Mainform closing, reason: {0}", e.CloseReason); - instance = null; + _instance = null; Exit(); } @@ -656,7 +656,7 @@ namespace Greenshot { } void CaptureFullScreen() { - CaptureHelper.CaptureFullscreen(true, conf.ScreenCaptureMode); + CaptureHelper.CaptureFullscreen(true, _conf.ScreenCaptureMode); } void CaptureLastRegion() { @@ -664,13 +664,13 @@ namespace Greenshot { } void CaptureIE() { - if (conf.IECapture) { + if (_conf.IECapture) { CaptureHelper.CaptureIE(true, null); } } void CaptureWindow() { - if (conf.CaptureWindowsInteractive) { + if (_conf.CaptureWindowsInteractive) { CaptureHelper.CaptureWindowInteractive(true); } else { CaptureHelper.CaptureWindow(true); @@ -680,54 +680,54 @@ namespace Greenshot { #region contextmenu - void ContextMenuOpening(object sender, System.ComponentModel.CancelEventArgs e) { + void ContextMenuOpening(object sender, CancelEventArgs e) { contextmenu_captureclipboard.Enabled = ClipboardHelper.ContainsImage(); contextmenu_capturelastregion.Enabled = RuntimeConfig.LastCapturedRegion != Rectangle.Empty; // IE context menu code try { - if (conf.IECapture && IECaptureHelper.IsIERunning()) { - this.contextmenu_captureie.Enabled = true; - this.contextmenu_captureiefromlist.Enabled = true; + if (_conf.IECapture && IECaptureHelper.IsIERunning()) { + contextmenu_captureie.Enabled = true; + contextmenu_captureiefromlist.Enabled = true; } else { - this.contextmenu_captureie.Enabled = false; - this.contextmenu_captureiefromlist.Enabled = false; + contextmenu_captureie.Enabled = false; + contextmenu_captureiefromlist.Enabled = false; } } catch (Exception ex) { LOG.WarnFormat("Problem accessing IE information: {0}", ex.Message); } // Multi-Screen captures - this.contextmenu_capturefullscreen.Click -= new System.EventHandler(this.CaptureFullScreenToolStripMenuItemClick); - this.contextmenu_capturefullscreen.DropDownOpening -= new System.EventHandler(MultiScreenDropDownOpening); - this.contextmenu_capturefullscreen.DropDownClosed -= new System.EventHandler(MultiScreenDropDownClosing); + contextmenu_capturefullscreen.Click -= CaptureFullScreenToolStripMenuItemClick; + contextmenu_capturefullscreen.DropDownOpening -= MultiScreenDropDownOpening; + contextmenu_capturefullscreen.DropDownClosed -= MultiScreenDropDownClosing; if (Screen.AllScreens.Length > 1) { - this.contextmenu_capturefullscreen.DropDownOpening += new System.EventHandler(MultiScreenDropDownOpening); - this.contextmenu_capturefullscreen.DropDownClosed += new System.EventHandler(MultiScreenDropDownClosing); + contextmenu_capturefullscreen.DropDownOpening += MultiScreenDropDownOpening; + contextmenu_capturefullscreen.DropDownClosed += MultiScreenDropDownClosing; } else { - this.contextmenu_capturefullscreen.Click += new System.EventHandler(this.CaptureFullScreenToolStripMenuItemClick); + contextmenu_capturefullscreen.Click += CaptureFullScreenToolStripMenuItemClick; } } void ContextMenuClosing(object sender, EventArgs e) { - this.contextmenu_captureiefromlist.DropDownItems.Clear(); - this.contextmenu_capturewindowfromlist.DropDownItems.Clear(); - cleanupThumbnail(); + contextmenu_captureiefromlist.DropDownItems.Clear(); + contextmenu_capturewindowfromlist.DropDownItems.Clear(); + CleanupThumbnail(); } /// /// Build a selectable list of IE tabs when we enter the menu item /// void CaptureIEMenuDropDownOpening(object sender, EventArgs e) { - if (!conf.IECapture) { + if (!_conf.IECapture) { return; } try { List> tabs = IECaptureHelper.GetBrowserTabs(); - this.contextmenu_captureiefromlist.DropDownItems.Clear(); + contextmenu_captureiefromlist.DropDownItems.Clear(); if (tabs.Count > 0) { - this.contextmenu_captureie.Enabled = true; - this.contextmenu_captureiefromlist.Enabled = true; + contextmenu_captureie.Enabled = true; + contextmenu_captureiefromlist.Enabled = true; Dictionary counter = new Dictionary(); foreach(KeyValuePair tabData in tabs) { @@ -735,8 +735,8 @@ namespace Greenshot { if (title == null) { continue; } - if (title.Length > conf.MaxMenuItemLength) { - title = title.Substring(0, Math.Min(title.Length, conf.MaxMenuItemLength)); + if (title.Length > _conf.MaxMenuItemLength) { + title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength)); } ToolStripItem captureIETabItem = contextmenu_captureiefromlist.DropDownItems.Add(title); int index; @@ -747,8 +747,8 @@ namespace Greenshot { } captureIETabItem.Image = tabData.Key.DisplayIcon; captureIETabItem.Tag = new KeyValuePair(tabData.Key, index++); - captureIETabItem.Click += new System.EventHandler(Contextmenu_captureiefromlist_Click); - this.contextmenu_captureiefromlist.DropDownItems.Add(captureIETabItem); + captureIETabItem.Click += Contextmenu_captureiefromlist_Click; + contextmenu_captureiefromlist.DropDownItems.Add(captureIETabItem); if (counter.ContainsKey(tabData.Key)) { counter[tabData.Key] = index; } else { @@ -756,8 +756,8 @@ namespace Greenshot { } } } else { - this.contextmenu_captureie.Enabled = false; - this.contextmenu_captureiefromlist.Enabled = false; + contextmenu_captureie.Enabled = false; + contextmenu_captureiefromlist.Enabled = false; } } catch (Exception ex) { LOG.WarnFormat("Problem accessing IE information: {0}", ex.Message); @@ -829,52 +829,54 @@ namespace Greenshot { } private void CaptureWindowFromListMenuDropDownClosed(object sender, EventArgs e) { - cleanupThumbnail(); + CleanupThumbnail(); } private void ShowThumbnailOnEnter(object sender, EventArgs e) { ToolStripMenuItem captureWindowItem = sender as ToolStripMenuItem; - WindowDetails window = captureWindowItem.Tag as WindowDetails; - if (thumbnailForm == null) { - thumbnailForm = new ThumbnailForm(); + if (captureWindowItem != null) { + WindowDetails window = captureWindowItem.Tag as WindowDetails; + if (_thumbnailForm == null) { + _thumbnailForm = new ThumbnailForm(); + } + _thumbnailForm.ShowThumbnail(window, captureWindowItem.GetCurrentParent().TopLevelControl); } - thumbnailForm.ShowThumbnail(window, captureWindowItem.GetCurrentParent().TopLevelControl); } private void HideThumbnailOnLeave(object sender, EventArgs e) { - if (thumbnailForm != null) { - thumbnailForm.Hide(); + if (_thumbnailForm != null) { + _thumbnailForm.Hide(); } } - private void cleanupThumbnail() { - if (thumbnailForm != null) { - thumbnailForm.Close(); - thumbnailForm = null; + private void CleanupThumbnail() { + if (_thumbnailForm != null) { + _thumbnailForm.Close(); + _thumbnailForm = null; } } public void AddCaptureWindowMenuItems(ToolStripMenuItem menuItem, EventHandler eventHandler) { menuItem.DropDownItems.Clear(); // check if thumbnailPreview is enabled and DWM is enabled - bool thumbnailPreview = conf.ThumnailPreview && DWM.isDWMEnabled(); + bool thumbnailPreview = _conf.ThumnailPreview && DWM.isDWMEnabled(); List windows = WindowDetails.GetTopLevelWindows(); foreach(WindowDetails window in windows) { string title = window.Text; if (title != null) { - if (title.Length > conf.MaxMenuItemLength) { - title = title.Substring(0, Math.Min(title.Length, conf.MaxMenuItemLength)); + if (title.Length > _conf.MaxMenuItemLength) { + title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength)); } ToolStripItem captureWindowItem = menuItem.DropDownItems.Add(title); captureWindowItem.Tag = window; captureWindowItem.Image = window.DisplayIcon; - captureWindowItem.Click += new System.EventHandler(eventHandler); + captureWindowItem.Click += eventHandler; // Only show preview when enabled if (thumbnailPreview) { - captureWindowItem.MouseEnter += new System.EventHandler(ShowThumbnailOnEnter); - captureWindowItem.MouseLeave += new System.EventHandler(HideThumbnailOnLeave); + captureWindowItem.MouseEnter += ShowThumbnailOnEnter; + captureWindowItem.MouseLeave += HideThumbnailOnLeave; } } } @@ -900,7 +902,7 @@ namespace Greenshot { void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) { BeginInvoke((MethodInvoker)delegate { - CaptureHelper.CaptureFullscreen(false, conf.ScreenCaptureMode); + CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode); }); } @@ -933,7 +935,7 @@ namespace Greenshot { } void Contextmenu_captureiefromlist_Click(object sender, EventArgs e) { - if (!conf.IECapture) { + if (!_conf.IECapture) { LOG.InfoFormat("IE Capture is disabled."); return; } @@ -983,17 +985,17 @@ namespace Greenshot { /// This is called indirectly from the context menu "Preferences" /// public void ShowSetting() { - if (settingsForm != null) { - WindowDetails.ToForeground(settingsForm.Handle); + if (_settingsForm != null) { + WindowDetails.ToForeground(_settingsForm.Handle); } else { try { - using (settingsForm = new SettingsForm()) { - if (settingsForm.ShowDialog() == DialogResult.OK) { + using (_settingsForm = new SettingsForm()) { + if (_settingsForm.ShowDialog() == DialogResult.OK) { InitializeQuickSettingsMenu(); } } } finally { - settingsForm = null; + _settingsForm = null; } } } @@ -1008,15 +1010,15 @@ namespace Greenshot { } public void ShowAbout() { - if (aboutForm != null) { - WindowDetails.ToForeground(aboutForm.Handle); + if (_aboutForm != null) { + WindowDetails.ToForeground(_aboutForm.Handle); } else { try { - using (aboutForm = new AboutForm()) { - aboutForm.ShowDialog(this); + using (_aboutForm = new AboutForm()) { + _aboutForm.ShowDialog(this); } } finally { - aboutForm = null; + _aboutForm = null; } } } @@ -1043,48 +1045,48 @@ namespace Greenshot { /// This needs to be called to initialize the quick settings menu entries /// private void InitializeQuickSettingsMenu() { - this.contextmenu_quicksettings.DropDownItems.Clear(); + contextmenu_quicksettings.DropDownItems.Clear(); - if (conf.DisableQuickSettings) { + if (_conf.DisableQuickSettings) { return; } // Only add if the value is not fixed - if (!conf.Values["CaptureMousepointer"].IsFixed) { + if (!_conf.Values["CaptureMousepointer"].IsFixed) { // For the capture mousecursor option ToolStripMenuSelectListItem captureMouseItem = new ToolStripMenuSelectListItem(); captureMouseItem.Text = Language.GetString("settings_capture_mousepointer"); - captureMouseItem.Checked = conf.CaptureMousepointer; + captureMouseItem.Checked = _conf.CaptureMousepointer; captureMouseItem.CheckOnClick = true; captureMouseItem.CheckStateChanged += delegate { - conf.CaptureMousepointer = captureMouseItem.Checked; + _conf.CaptureMousepointer = captureMouseItem.Checked; }; - this.contextmenu_quicksettings.DropDownItems.Add(captureMouseItem); + contextmenu_quicksettings.DropDownItems.Add(captureMouseItem); } - ToolStripMenuSelectList selectList = null; - if (!conf.Values["Destinations"].IsFixed) { + ToolStripMenuSelectList selectList; + if (!_conf.Values["Destinations"].IsFixed) { // screenshot destination selectList = new ToolStripMenuSelectList("destinations", true); selectList.Text = Language.GetString(LangKey.settings_destination); // Working with IDestination: foreach (IDestination destination in DestinationHelper.GetAllDestinations()) { - selectList.AddItem(destination.Description, destination, conf.OutputDestinations.Contains(destination.Designation)); + selectList.AddItem(destination.Description, destination, _conf.OutputDestinations.Contains(destination.Designation)); } - selectList.CheckedChanged += new EventHandler(this.QuickSettingDestinationChanged); - this.contextmenu_quicksettings.DropDownItems.Add(selectList); + selectList.CheckedChanged += QuickSettingDestinationChanged; + contextmenu_quicksettings.DropDownItems.Add(selectList); } - if (!conf.Values["WindowCaptureMode"].IsFixed) { + if (!_conf.Values["WindowCaptureMode"].IsFixed) { // Capture Modes selectList = new ToolStripMenuSelectList("capturemodes", false); selectList.Text = Language.GetString(LangKey.settings_window_capture_mode); string enumTypeName = typeof(WindowCaptureMode).Name; foreach (WindowCaptureMode captureMode in Enum.GetValues(typeof(WindowCaptureMode))) { - selectList.AddItem(Language.GetString(enumTypeName + "." + captureMode.ToString()), captureMode, conf.WindowCaptureMode == captureMode); + selectList.AddItem(Language.GetString(enumTypeName + "." + captureMode.ToString()), captureMode, _conf.WindowCaptureMode == captureMode); } - selectList.CheckedChanged += new EventHandler(this.QuickSettingCaptureModeChanged); - this.contextmenu_quicksettings.DropDownItems.Add(selectList); + selectList.CheckedChanged += QuickSettingCaptureModeChanged; + contextmenu_quicksettings.DropDownItems.Add(selectList); } // print options @@ -1092,34 +1094,34 @@ namespace Greenshot { selectList.Text = Language.GetString(LangKey.settings_printoptions); IniValue iniValue; - foreach(string propertyName in conf.Values.Keys) { + foreach(string propertyName in _conf.Values.Keys) { if (propertyName.StartsWith("OutputPrint")) { - iniValue = conf.Values[propertyName]; + iniValue = _conf.Values[propertyName]; if (iniValue.Attributes.LanguageKey != null && !iniValue.IsFixed) { selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); } } } if (selectList.DropDownItems.Count > 0) { - selectList.CheckedChanged += new EventHandler(this.QuickSettingBoolItemChanged); - this.contextmenu_quicksettings.DropDownItems.Add(selectList); + selectList.CheckedChanged += QuickSettingBoolItemChanged; + contextmenu_quicksettings.DropDownItems.Add(selectList); } // effects selectList = new ToolStripMenuSelectList("effects",true); selectList.Text = Language.GetString(LangKey.settings_visualization); - iniValue = conf.Values["PlayCameraSound"]; + iniValue = _conf.Values["PlayCameraSound"]; if (!iniValue.IsFixed) { selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); } - iniValue = conf.Values["ShowTrayNotification"]; + iniValue = _conf.Values["ShowTrayNotification"]; if (!iniValue.IsFixed) { selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); } if (selectList.DropDownItems.Count > 0) { - selectList.CheckedChanged += new EventHandler(this.QuickSettingBoolItemChanged); - this.contextmenu_quicksettings.DropDownItems.Add(selectList); + selectList.CheckedChanged += QuickSettingBoolItemChanged; + contextmenu_quicksettings.DropDownItems.Add(selectList); } } @@ -1127,7 +1129,7 @@ namespace Greenshot { ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item; WindowCaptureMode windowsCaptureMode = (WindowCaptureMode)item.Data; if (item.Checked) { - conf.WindowCaptureMode = windowsCaptureMode; + _conf.WindowCaptureMode = windowsCaptureMode; } } @@ -1146,24 +1148,24 @@ namespace Greenshot { if (item.Checked) { if (selectedDestination.Designation.Equals(PickerDestination.DESIGNATION)) { // If the item is the destination picker, remove all others - conf.OutputDestinations.Clear(); + _conf.OutputDestinations.Clear(); } else { // If the item is not the destination picker, remove the picker - conf.OutputDestinations.Remove(PickerDestination.DESIGNATION); + _conf.OutputDestinations.Remove(PickerDestination.DESIGNATION); } // Checked an item, add if the destination is not yet selected - if (!conf.OutputDestinations.Contains(selectedDestination.Designation)) { - conf.OutputDestinations.Add(selectedDestination.Designation); + if (!_conf.OutputDestinations.Contains(selectedDestination.Designation)) { + _conf.OutputDestinations.Add(selectedDestination.Designation); } } else { // deselected a destination, only remove if it was selected - if (conf.OutputDestinations.Contains(selectedDestination.Designation)) { - conf.OutputDestinations.Remove(selectedDestination.Designation); + if (_conf.OutputDestinations.Contains(selectedDestination.Designation)) { + _conf.OutputDestinations.Remove(selectedDestination.Designation); } } // Check if something was selected, if not make the picker the default - if (conf.OutputDestinations == null || conf.OutputDestinations.Count == 0) { - conf.OutputDestinations.Add(PickerDestination.DESIGNATION); + if (_conf.OutputDestinations == null || _conf.OutputDestinations.Count == 0) { + _conf.OutputDestinations.Add(PickerDestination.DESIGNATION); } IniConfig.Save(); @@ -1196,24 +1198,24 @@ namespace Greenshot { return; } // The right button will automatically be handled with the context menu, here we only check the left. - if (conf.DoubleClickAction == ClickActions.DO_NOTHING) { + if (_conf.DoubleClickAction == ClickActions.DO_NOTHING) { // As there isn't a double-click we can start the Left click - NotifyIconClick(conf.LeftClickAction); + NotifyIconClick(_conf.LeftClickAction); // ready with the test return; } // If the timer is enabled we are waiting for a double click... - if (doubleClickTimer.Enabled) { + if (_doubleClickTimer.Enabled) { // User clicked a second time before the timer tick: Double-click! - doubleClickTimer.Elapsed -= NotifyIconSingleClickTest; - doubleClickTimer.Stop(); - NotifyIconClick(conf.DoubleClickAction); + _doubleClickTimer.Elapsed -= NotifyIconSingleClickTest; + _doubleClickTimer.Stop(); + NotifyIconClick(_conf.DoubleClickAction); } else { // User clicked without a timer, set the timer and if it ticks it was a single click // Create timer, if it ticks before the NotifyIconClickTest is called again we have a single click - doubleClickTimer.Elapsed += NotifyIconSingleClickTest; - doubleClickTimer.Interval = SystemInformation.DoubleClickTime; - doubleClickTimer.Start(); + _doubleClickTimer.Elapsed += NotifyIconSingleClickTest; + _doubleClickTimer.Interval = SystemInformation.DoubleClickTime; + _doubleClickTimer.Start(); } } @@ -1223,10 +1225,10 @@ namespace Greenshot { /// /// private void NotifyIconSingleClickTest(object sender, EventArgs e) { - doubleClickTimer.Elapsed -= NotifyIconSingleClickTest; - doubleClickTimer.Stop(); + _doubleClickTimer.Elapsed -= NotifyIconSingleClickTest; + _doubleClickTimer.Stop(); BeginInvoke((MethodInvoker)delegate { - NotifyIconClick(conf.LeftClickAction); + NotifyIconClick(_conf.LeftClickAction); }); } @@ -1237,25 +1239,27 @@ namespace Greenshot { switch (clickAction) { case ClickActions.OPEN_LAST_IN_EXPLORER: string path = null; - string configPath = FilenameHelper.FillVariables(conf.OutputFilePath, false); - string lastFilePath = Path.GetDirectoryName(conf.OutputFileAsFullpath); - if (Directory.Exists(lastFilePath)) { + string configPath = FilenameHelper.FillVariables(_conf.OutputFilePath, false); + string lastFilePath = Path.GetDirectoryName(_conf.OutputFileAsFullpath); + if (lastFilePath != null && Directory.Exists(lastFilePath)) { path = lastFilePath; } else if (Directory.Exists(configPath)) { path = configPath; } - try { - System.Diagnostics.Process.Start(path); - } catch (Exception ex) { - // Make sure we show what we tried to open in the exception - ex.Data.Add("path", path); - throw; + if (path != null) { + try { + Process.Start(path); + } catch (Exception ex) { + // Make sure we show what we tried to open in the exception + ex.Data.Add("path", path); + throw; + } } break; case ClickActions.OPEN_LAST_IN_EDITOR: - if (File.Exists(conf.OutputFileAsFullpath)) { - CaptureHelper.CaptureFile(conf.OutputFileAsFullpath, DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); + if (File.Exists(_conf.OutputFileAsFullpath)) { + CaptureHelper.CaptureFile(_conf.OutputFileAsFullpath, DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); } break; case ClickActions.OPEN_SETTINGS: @@ -1265,9 +1269,6 @@ namespace Greenshot { MethodInfo oMethodInfo = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic); oMethodInfo.Invoke(notifyIcon, null); break; - default: - // Do nothing - break; } } @@ -1275,11 +1276,12 @@ namespace Greenshot { /// The Contextmenu_OpenRecent currently opens the last know save location /// private void Contextmenu_OpenRecent(object sender, EventArgs eventArgs) { - string path = FilenameHelper.FillVariables(conf.OutputFilePath, false); + string path = FilenameHelper.FillVariables(_conf.OutputFilePath, false); // Fix for #1470, problems with a drive which is no longer available try { - string lastFilePath = Path.GetDirectoryName(conf.OutputFileAsFullpath); - if (Directory.Exists(lastFilePath)) { + string lastFilePath = Path.GetDirectoryName(_conf.OutputFileAsFullpath); + + if (lastFilePath != null && Directory.Exists(lastFilePath)) { path = lastFilePath; } else if (!Directory.Exists(path)) { // What do I open when nothing can be found? Right, nothing... @@ -1290,7 +1292,7 @@ namespace Greenshot { } LOG.Debug("DoubleClick was called! Starting: " + path); try { - System.Diagnostics.Process.Start(path); + Process.Start(path); } catch (Exception ex) { // Make sure we show what we tried to open in the exception ex.Data.Add("path", path); @@ -1309,14 +1311,15 @@ namespace Greenshot { // Close all open forms (except this), use a separate List to make sure we don't get a "InvalidOperationException: Collection was modified" List
formsToClose = new List(); foreach(Form form in Application.OpenForms) { - if (form.Handle != this.Handle && !form.GetType().Equals(typeof(Greenshot.ImageEditorForm))) { + if (form.Handle != Handle && !form.GetType().Equals(typeof(ImageEditorForm))) { formsToClose.Add(form); } } foreach(Form form in formsToClose) { try { LOG.InfoFormat("Closing form: {0}", form.Name); - this.Invoke((MethodInvoker) delegate { form.Close(); }); + Form formCapturedVariable = form; + Invoke((MethodInvoker)delegate { formCapturedVariable.Close(); }); } catch (Exception e) { LOG.Error("Error closing form!", e); } @@ -1377,14 +1380,14 @@ namespace Greenshot { /// /// private void BackgroundWorkerTimerTick(object sender, EventArgs e) { - if (conf.MinimizeWorkingSetSize) { + if (_conf.MinimizeWorkingSetSize) { LOG.Info("Calling EmptyWorkingSet"); PsAPI.EmptyWorkingSet(Process.GetCurrentProcess().Handle); } if (UpdateHelper.IsUpdateCheckNeeded()) { LOG.Debug("BackgroundWorkerTimerTick checking for update"); // Start update check in the background - Thread backgroundTask = new Thread (new ThreadStart(UpdateHelper.CheckAndAskForUpdate)); + Thread backgroundTask = new Thread (UpdateHelper.CheckAndAskForUpdate); backgroundTask.Name = "Update check"; backgroundTask.IsBackground = true; backgroundTask.Start(); diff --git a/Greenshot/Forms/PrintOptionsDialog.cs b/Greenshot/Forms/PrintOptionsDialog.cs index 2bf6528a4..40202d10b 100644 --- a/Greenshot/Forms/PrintOptionsDialog.cs +++ b/Greenshot/Forms/PrintOptionsDialog.cs @@ -20,9 +20,8 @@ */ using System; using System.Windows.Forms; -using Greenshot.Configuration; -using GreenshotPlugin.Core; using Greenshot.IniFile; +using GreenshotPlugin.Core; namespace Greenshot.Forms { /// @@ -34,14 +33,14 @@ namespace Greenshot.Forms { // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); - this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); - this.checkbox_dontaskagain.Checked = false; + Icon = GreenshotResources.getGreenshotIcon(); + checkbox_dontaskagain.Checked = false; } void Button_okClick(object sender, EventArgs e) { // update config - coreConfiguration.OutputPrintPromptOptions = !this.checkbox_dontaskagain.Checked; + coreConfiguration.OutputPrintPromptOptions = !checkbox_dontaskagain.Checked; IniConfig.Save(); DialogResult = DialogResult.OK; } diff --git a/Greenshot/Forms/SettingsForm.cs b/Greenshot/Forms/SettingsForm.cs index 87bd7920f..c32e730e6 100644 --- a/Greenshot/Forms/SettingsForm.cs +++ b/Greenshot/Forms/SettingsForm.cs @@ -19,8 +19,10 @@ * along with this program. If not, see . */ using System; +using System.Collections; using System.Collections.Generic; using System.Drawing; +using System.Globalization; using System.IO; using System.Windows.Forms; @@ -33,19 +35,18 @@ using GreenshotPlugin.UnmanagedHelpers; using Greenshot.Plugin; using Greenshot.IniFile; using System.Text.RegularExpressions; -using Greenshot.Controls; +using log4net; namespace Greenshot { /// /// Description of SettingsForm. /// public partial class SettingsForm : BaseForm { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(SettingsForm)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); - private ToolTip toolTip = new ToolTip(); - private bool inHotkey = false; + private static ILog LOG = LogManager.GetLogger(typeof(SettingsForm)); + private readonly ToolTip _toolTip = new ToolTip(); + private bool _inHotkey; - public SettingsForm() : base() { + public SettingsForm() { InitializeComponent(); // Make sure the store isn't called to early, that's why we do it manually @@ -54,26 +55,26 @@ namespace Greenshot { protected override void OnLoad(EventArgs e) { base.OnLoad(e); - this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); + Icon = GreenshotResources.getGreenshotIcon(); // Fix for Vista/XP differences if (Environment.OSVersion.Version.Major >= 6) { - this.trackBarJpegQuality.BackColor = System.Drawing.SystemColors.Window; + trackBarJpegQuality.BackColor = SystemColors.Window; } else { - this.trackBarJpegQuality.BackColor = System.Drawing.SystemColors.Control; + trackBarJpegQuality.BackColor = SystemColors.Control; } // This makes it possible to still capture the settings screen - this.fullscreen_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; - this.fullscreen_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; - this.window_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; - this.window_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; - this.region_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; - this.region_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; - this.ie_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; - this.ie_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; - this.lastregion_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; - this.lastregion_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; + fullscreen_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; + fullscreen_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; + window_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; + window_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; + region_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; + region_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; + ie_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; + ie_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; + lastregion_hotkeyControl.Enter += delegate { EnterHotkeyControl(); }; + lastregion_hotkeyControl.Leave += delegate { LeaveHotkeyControl(); }; DisplayPluginTab(); UpdateUI(); @@ -83,19 +84,19 @@ namespace Greenshot { } private void EnterHotkeyControl() { - GreenshotPlugin.Controls.HotkeyControl.UnregisterHotkeys(); - inHotkey = true; + HotkeyControl.UnregisterHotkeys(); + _inHotkey = true; } private void LeaveHotkeyControl() { MainForm.RegisterHotkeys(); - inHotkey = false; + _inHotkey = false; } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { switch (keyData) { case Keys.Escape: - if (!inHotkey) { + if (!_inHotkey) { DialogResult = DialogResult.Cancel; } else { return base.ProcessCmdKey(ref msg, keyData); @@ -107,17 +108,6 @@ namespace Greenshot { return true; } - /// - /// This is a method to popululate the ComboBox - /// with the items from the enumeration - /// - /// ComboBox to populate - /// Enum to populate with - private void PopulateComboBox(ComboBox comboBox) where ET : struct { - ET[] availableValues = (ET[])Enum.GetValues(typeof(ET)); - PopulateComboBox(comboBox, availableValues, availableValues[0]); - } - /// /// This is a method to popululate the ComboBox /// with the items from the enumeration @@ -126,7 +116,6 @@ namespace Greenshot { /// Enum to populate with private void PopulateComboBox(ComboBox comboBox, ET[] availableValues, ET selectedValue) where ET : struct { comboBox.Items.Clear(); - string enumTypeName = typeof(ET).Name; foreach(ET enumValue in availableValues) { comboBox.Items.Add(Language.Translate(enumValue)); } @@ -161,16 +150,16 @@ namespace Greenshot { if (coreConfiguration.WindowCaptureMode == WindowCaptureMode.Aero || coreConfiguration.WindowCaptureMode == WindowCaptureMode.AeroTransparent) { coreConfiguration.WindowCaptureMode = WindowCaptureMode.GDI; } - availableModes = new WindowCaptureMode[]{WindowCaptureMode.Auto, WindowCaptureMode.Screen, WindowCaptureMode.GDI}; + availableModes = new[]{WindowCaptureMode.Auto, WindowCaptureMode.Screen, WindowCaptureMode.GDI}; } else { - availableModes = new WindowCaptureMode[]{WindowCaptureMode.Auto, WindowCaptureMode.Screen, WindowCaptureMode.GDI, WindowCaptureMode.Aero, WindowCaptureMode.AeroTransparent}; + availableModes = new[]{WindowCaptureMode.Auto, WindowCaptureMode.Screen, WindowCaptureMode.GDI, WindowCaptureMode.Aero, WindowCaptureMode.AeroTransparent}; } - PopulateComboBox(combobox_window_capture_mode, availableModes, selectedWindowCaptureMode); + PopulateComboBox(combobox_window_capture_mode, availableModes, selectedWindowCaptureMode); } private void DisplayPluginTab() { if (!PluginHelper.Instance.HasPlugins()) { - this.tabcontrol.TabPages.Remove(tab_plugins); + tabcontrol.TabPages.Remove(tab_plugins); } else { // Draw the Plugin listview listview_plugins.BeginUpdate(); @@ -184,7 +173,7 @@ namespace Greenshot { foreach (string column in columns) { listview_plugins.Columns.Add(column); } - PluginHelper.Instance.FillListview(this.listview_plugins); + PluginHelper.Instance.FillListview(listview_plugins); // Maximize Column size! for (int i = 0; i < listview_plugins.Columns.Count; i++) { listview_plugins.AutoResizeColumn(i, ColumnHeaderAutoResizeStyle.ColumnContent); @@ -209,26 +198,26 @@ namespace Greenshot { if (coreConfiguration.HideExpertSettings) { tabcontrol.Controls.Remove(tab_expert); } - toolTip.SetToolTip(label_language, Language.GetString(LangKey.settings_tooltip_language)); - toolTip.SetToolTip(label_storagelocation, Language.GetString(LangKey.settings_tooltip_storagelocation)); - toolTip.SetToolTip(label_screenshotname, Language.GetString(LangKey.settings_tooltip_filenamepattern)); - toolTip.SetToolTip(label_primaryimageformat, Language.GetString(LangKey.settings_tooltip_primaryimageformat)); + _toolTip.SetToolTip(label_language, Language.GetString(LangKey.settings_tooltip_language)); + _toolTip.SetToolTip(label_storagelocation, Language.GetString(LangKey.settings_tooltip_storagelocation)); + _toolTip.SetToolTip(label_screenshotname, Language.GetString(LangKey.settings_tooltip_filenamepattern)); + _toolTip.SetToolTip(label_primaryimageformat, Language.GetString(LangKey.settings_tooltip_primaryimageformat)); // Removing, otherwise we keep getting the event multiple times! - this.combobox_language.SelectedIndexChanged -= new System.EventHandler(this.Combobox_languageSelectedIndexChanged); + combobox_language.SelectedIndexChanged -= Combobox_languageSelectedIndexChanged; // Initialize the Language ComboBox - this.combobox_language.DisplayMember = "Description"; - this.combobox_language.ValueMember = "Ietf"; + combobox_language.DisplayMember = "Description"; + combobox_language.ValueMember = "Ietf"; // Set datasource last to prevent problems // See: http://www.codeproject.com/KB/database/scomlistcontrolbinding.aspx?fid=111644 - this.combobox_language.DataSource = Language.SupportedLanguages; + combobox_language.DataSource = Language.SupportedLanguages; if (Language.CurrentLanguage != null) { - this.combobox_language.SelectedValue = Language.CurrentLanguage; + combobox_language.SelectedValue = Language.CurrentLanguage; } // Delaying the SelectedIndexChanged events untill all is initiated - this.combobox_language.SelectedIndexChanged += new System.EventHandler(this.Combobox_languageSelectedIndexChanged); + combobox_language.SelectedIndexChanged += Combobox_languageSelectedIndexChanged; UpdateDestinationDescriptions(); UpdateClipboardFormatDescriptions(); } @@ -242,15 +231,15 @@ namespace Greenshot { } else { // "Added" feature #3547158 if (Environment.OSVersion.Version.Major >= 6) { - this.textbox_storagelocation.BackColor = System.Drawing.SystemColors.Window; + textbox_storagelocation.BackColor = SystemColors.Window; } else { - this.textbox_storagelocation.BackColor = System.Drawing.SystemColors.Control; + textbox_storagelocation.BackColor = SystemColors.Control; } } return settingsOk; } - private void StorageLocationChanged(object sender, System.EventArgs e) { + private void StorageLocationChanged(object sender, EventArgs e) { CheckSettings(); } @@ -259,8 +248,10 @@ namespace Greenshot { /// private void UpdateDestinationDescriptions() { foreach (ListViewItem item in listview_destinations.Items) { - IDestination destination = item.Tag as IDestination; - item.Text = destination.Description; + IDestination destinationFromTag = item.Tag as IDestination; + if (destinationFromTag != null) { + item.Text = destinationFromTag.Description; + } } } @@ -289,24 +280,24 @@ namespace Greenshot { ImageList imageList = new ImageList(); listview_destinations.SmallImageList = imageList; int imageNr = -1; - foreach (IDestination destination in DestinationHelper.GetAllDestinations()) { - Image destinationImage = destination.DisplayIcon; + foreach (IDestination currentDestination in DestinationHelper.GetAllDestinations()) { + Image destinationImage = currentDestination.DisplayIcon; if (destinationImage != null) { - imageList.Images.Add(destination.DisplayIcon); + imageList.Images.Add(currentDestination.DisplayIcon); imageNr++; } - if (PickerDestination.DESIGNATION.Equals(destination.Designation)) { - checkbox_picker.Checked = coreConfiguration.OutputDestinations.Contains(destination.Designation); - checkbox_picker.Text = destination.Description; + if (PickerDestination.DESIGNATION.Equals(currentDestination.Designation)) { + checkbox_picker.Checked = coreConfiguration.OutputDestinations.Contains(currentDestination.Designation); + checkbox_picker.Text = currentDestination.Description; } else { ListViewItem item; if (destinationImage != null) { - item = listview_destinations.Items.Add(destination.Description, imageNr); + item = listview_destinations.Items.Add(currentDestination.Description, imageNr); } else { - item = listview_destinations.Items.Add(destination.Description); + item = listview_destinations.Items.Add(currentDestination.Description); } - item.Tag = destination; - item.Checked = coreConfiguration.OutputDestinations.Contains(destination.Designation); + item.Tag = currentDestination; + item.Checked = coreConfiguration.OutputDestinations.Contains(currentDestination.Designation); } } if (checkbox_picker.Checked) { @@ -358,18 +349,18 @@ namespace Greenshot { checkbox_autostartshortcut.Checked = false; } else { // Autostart checkbox logic. - if (StartupHelper.hasRunAll()) { + if (StartupHelper.HasRunAll()) { // Remove runUser if we already have a run under all - StartupHelper.deleteRunUser(); - checkbox_autostartshortcut.Enabled = StartupHelper.canWriteRunAll(); + StartupHelper.DeleteRunUser(); + checkbox_autostartshortcut.Enabled = StartupHelper.CanWriteRunAll(); checkbox_autostartshortcut.Checked = true; // We already checked this } else if (StartupHelper.IsInStartupFolder()) { checkbox_autostartshortcut.Enabled = false; checkbox_autostartshortcut.Checked = true; // We already checked this } else { // No run for all, enable the checkbox and set it to true if the current user has a key - checkbox_autostartshortcut.Enabled = StartupHelper.canWriteRunUser(); - checkbox_autostartshortcut.Checked = StartupHelper.hasRunUser(); + checkbox_autostartshortcut.Enabled = StartupHelper.CanWriteRunUser(); + checkbox_autostartshortcut.Checked = StartupHelper.HasRunUser(); } } @@ -409,9 +400,9 @@ namespace Greenshot { foreach(int index in listview_destinations.CheckedIndices) { ListViewItem item = listview_destinations.Items[index]; - IDestination destination = item.Tag as IDestination; - if (item.Checked) { - destinations.Add(destination.Designation); + IDestination destinationFromTag = item.Tag as IDestination; + if (item.Checked && destinationFromTag != null) { + destinations.Add(destinationFromTag.Designation); } } coreConfiguration.OutputDestinations = destinations; @@ -423,16 +414,16 @@ namespace Greenshot { if (checkbox_autostartshortcut.Checked) { // It's checked, so we set the RunUser if the RunAll isn't set. // Do this every time, so the executable is correct. - if (!StartupHelper.hasRunAll()) { - StartupHelper.setRunUser(); + if (!StartupHelper.HasRunAll()) { + StartupHelper.SetRunUser(); } } else { // Delete both settings if it's unchecked - if (StartupHelper.hasRunAll()) { - StartupHelper.deleteRunAll(); + if (StartupHelper.HasRunAll()) { + StartupHelper.DeleteRunAll(); } - if (StartupHelper.hasRunUser()) { - StartupHelper.deleteRunUser(); + if (StartupHelper.HasRunUser()) { + StartupHelper.DeleteRunUser(); } } } catch (Exception e) { @@ -440,13 +431,13 @@ namespace Greenshot { } } - void Settings_cancelClick(object sender, System.EventArgs e) { + void Settings_cancelClick(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } - void Settings_okayClick(object sender, System.EventArgs e) { + void Settings_okayClick(object sender, EventArgs e) { if (CheckSettings()) { - GreenshotPlugin.Controls.HotkeyControl.UnregisterHotkeys(); + HotkeyControl.UnregisterHotkeys(); SaveSettings(); StoreFields(); MainForm.RegisterHotkeys(); @@ -455,23 +446,23 @@ namespace Greenshot { MainForm.Instance.UpdateUI(); DialogResult = DialogResult.OK; } else { - this.tabcontrol.SelectTab(this.tab_output); + tabcontrol.SelectTab(tab_output); } } - void BrowseClick(object sender, System.EventArgs e) { + void BrowseClick(object sender, EventArgs e) { // Get the storage location and replace the environment variables - this.folderBrowserDialog1.SelectedPath = FilenameHelper.FillVariables(this.textbox_storagelocation.Text, false); - if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK) { + folderBrowserDialog1.SelectedPath = FilenameHelper.FillVariables(textbox_storagelocation.Text, false); + if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { // Only change if there is a change, otherwise we might overwrite the environment variables - if (this.folderBrowserDialog1.SelectedPath != null && !this.folderBrowserDialog1.SelectedPath.Equals(FilenameHelper.FillVariables(this.textbox_storagelocation.Text, false))) { - this.textbox_storagelocation.Text = this.folderBrowserDialog1.SelectedPath; + if (folderBrowserDialog1.SelectedPath != null && !folderBrowserDialog1.SelectedPath.Equals(FilenameHelper.FillVariables(textbox_storagelocation.Text, false))) { + textbox_storagelocation.Text = folderBrowserDialog1.SelectedPath; } } } - void TrackBarJpegQualityScroll(object sender, System.EventArgs e) { - textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(); + void TrackBarJpegQualityScroll(object sender, EventArgs e) { + textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(CultureInfo.InvariantCulture); } @@ -536,8 +527,8 @@ namespace Greenshot { foreach(int index in listview_destinations.CheckedIndices) { ListViewItem item = listview_destinations.Items[index]; - IDestination destination = item.Tag as IDestination; - if (destination.Designation.Equals(ClipboardDestination.DESIGNATION)) { + IDestination destinationFromTag = item.Tag as IDestination; + if (destinationFromTag != null && destinationFromTag.Designation.Equals(ClipboardDestination.DESIGNATION)) { clipboardDestinationChecked = true; break; } @@ -595,7 +586,9 @@ namespace Greenshot { /// private void checkbox_enableexpert_CheckedChanged(object sender, EventArgs e) { CheckBox checkBox = sender as CheckBox; - ExpertSettingsEnableState(checkBox.Checked); + if (checkBox != null) { + ExpertSettingsEnableState(checkBox.Checked); + } } private void radiobutton_CheckedChanged(object sender, EventArgs e) { @@ -603,13 +596,13 @@ namespace Greenshot { } } - public class ListviewWithDestinationComparer : System.Collections.IComparer { + public class ListviewWithDestinationComparer : IComparer { public int Compare(object x, object y) { if (!(x is ListViewItem)) { - return (0); + return 0; } if (!(y is ListViewItem)) { - return (0); + return 0; } ListViewItem l1 = (ListViewItem)x; @@ -621,10 +614,13 @@ namespace Greenshot { if (secondDestination == null) { return 1; } - if (firstDestination.Priority == secondDestination.Priority) { + if (firstDestination != null && firstDestination.Priority == secondDestination.Priority) { return firstDestination.Description.CompareTo(secondDestination.Description); } - return firstDestination.Priority - secondDestination.Priority; + if (firstDestination != null) { + return firstDestination.Priority - secondDestination.Priority; + } + return 0; } } } diff --git a/Greenshot/Forms/ToolStripMenuSelectList.cs b/Greenshot/Forms/ToolStripMenuSelectList.cs index b0e29949f..0027925c1 100644 --- a/Greenshot/Forms/ToolStripMenuSelectList.cs +++ b/Greenshot/Forms/ToolStripMenuSelectList.cs @@ -113,7 +113,7 @@ namespace Greenshot.Forms { } } - private void ItemCheckStateChanged(object sender, System.EventArgs e) { + private void ItemCheckStateChanged(object sender, EventArgs e) { if (updateInProgress) { return; } @@ -141,7 +141,7 @@ namespace Greenshot.Forms { newItem.Text = label; newItem.Image = image; newItem.CheckOnClick = true; - newItem.CheckStateChanged += new System.EventHandler(this.ItemCheckStateChanged); + newItem.CheckStateChanged += ItemCheckStateChanged; newItem.Data = data; if (isChecked) { if (!multiCheckAllowed) { @@ -151,7 +151,7 @@ namespace Greenshot.Forms { } newItem.Checked = isChecked; } - this.DropDownItems.Add(newItem); + DropDownItems.Add(newItem); } /// @@ -222,7 +222,7 @@ namespace Greenshot.Forms { } } - public class ItemCheckedChangedEventArgs : System.EventArgs { + public class ItemCheckedChangedEventArgs : EventArgs { public ToolStripMenuSelectListItem Item; public ItemCheckedChangedEventArgs(ToolStripMenuSelectListItem item) { Item = item; diff --git a/Greenshot/GreenshotMain.cs b/Greenshot/GreenshotMain.cs index e097bb9ff..d131c943b 100644 --- a/Greenshot/GreenshotMain.cs +++ b/Greenshot/GreenshotMain.cs @@ -29,7 +29,7 @@ namespace Greenshot { /// public class GreenshotMain { static GreenshotMain() { - AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); + AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { diff --git a/Greenshot/Help/HelpFileLoader.cs b/Greenshot/Help/HelpFileLoader.cs index 091c991f6..931e965d3 100644 --- a/Greenshot/Help/HelpFileLoader.cs +++ b/Greenshot/Help/HelpFileLoader.cs @@ -6,12 +6,11 @@ * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ -using Greenshot.Configuration; + using GreenshotPlugin.Core; -using System; using System.Diagnostics; using System.Net; -using System.Windows.Forms; +using log4net; namespace Greenshot.Help { @@ -21,7 +20,7 @@ namespace Greenshot.Help public sealed class HelpFileLoader { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(HelpFileLoader)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(HelpFileLoader)); private const string EXT_HELP_URL = @"http://getgreenshot.org/help/"; diff --git a/Greenshot/Helpers/AviHelper.cs b/Greenshot/Helpers/AviHelper.cs index 29b307ae8..9884b49c9 100644 --- a/Greenshot/Helpers/AviHelper.cs +++ b/Greenshot/Helpers/AviHelper.cs @@ -7,8 +7,6 @@ // // using System; -using System.Drawing; -using System.Drawing.Imaging; using System.Runtime.InteropServices; using GreenshotPlugin.UnmanagedHelpers; diff --git a/Greenshot/Helpers/CaptureHelper.cs b/Greenshot/Helpers/CaptureHelper.cs index aa1ff36f2..97fec59e4 100644 --- a/Greenshot/Helpers/CaptureHelper.cs +++ b/Greenshot/Helpers/CaptureHelper.cs @@ -18,43 +18,40 @@ * 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.Diagnostics; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Printing; -using System.IO; -using System.Threading; -using System.Windows.Forms; + using Greenshot.Configuration; using Greenshot.Destinations; using Greenshot.Drawing; using Greenshot.Forms; -using Greenshot.Helpers; +using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; using GreenshotPlugin.UnmanagedHelpers; -using Greenshot.IniFile; -using Greenshot.Interop; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Threading; +using System.Windows.Forms; +using log4net; namespace Greenshot.Helpers { /// /// CaptureHelper contains all the capture logic /// public class CaptureHelper { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(CaptureHelper)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureHelper)); private static 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(); - private WindowDetails selectedCaptureWindow = null; - private Rectangle captureRect = Rectangle.Empty; - private bool captureMouseCursor = false; - private ICapture capture = null; - private CaptureMode captureMode; - private ScreenCaptureMode screenCaptureMode = ScreenCaptureMode.Auto; - private Thread windowDetailsThread = null; + private List _windows = new List(); + private WindowDetails _selectedCaptureWindow; + private Rectangle _captureRect = Rectangle.Empty; + private readonly bool _captureMouseCursor; + private ICapture _capture; + private CaptureMode _captureMode; + private ScreenCaptureMode _screenCaptureMode = ScreenCaptureMode.Auto; /// /// The public accessible Dispose @@ -76,10 +73,9 @@ namespace Greenshot.Helpers { if (disposing) { // Cleanup } - windows = null; - selectedCaptureWindow = null; - windowDetailsThread = null; - capture = null; + _windows = null; + _selectedCaptureWindow = null; + _capture = null; } public static void CaptureClipboard() { new CaptureHelper(CaptureMode.Clipboard).MakeCapture(); @@ -96,7 +92,7 @@ namespace Greenshot.Helpers { } public static void CaptureFullscreen(bool captureMouse, ScreenCaptureMode screenCaptureMode) { CaptureHelper captureHelper = new CaptureHelper(CaptureMode.FullScreen, captureMouse); - captureHelper.screenCaptureMode = screenCaptureMode; + captureHelper._screenCaptureMode = screenCaptureMode; captureHelper.MakeCapture(); } public static void CaptureLastRegion(bool captureMouse) { @@ -133,39 +129,39 @@ namespace Greenshot.Helpers { public static void ImportCapture(ICapture captureToImport) { CaptureHelper captureHelper = new CaptureHelper(CaptureMode.File); - captureHelper.capture = captureToImport; + captureHelper._capture = captureToImport; captureHelper.HandleCapture(); } public CaptureHelper AddDestination(IDestination destination) { - capture.CaptureDetails.AddDestination(destination); + _capture.CaptureDetails.AddDestination(destination); return this; } public CaptureHelper(CaptureMode captureMode) { - this.captureMode = captureMode; - capture = new Capture(); + _captureMode = captureMode; + _capture = new Capture(); } public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor) : this(captureMode) { - this.captureMouseCursor = captureMouseCursor; + _captureMouseCursor = captureMouseCursor; } public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor, ScreenCaptureMode screenCaptureMode) : this(captureMode) { - this.captureMouseCursor = captureMouseCursor; - this.screenCaptureMode = screenCaptureMode; + _captureMouseCursor = captureMouseCursor; + _screenCaptureMode = screenCaptureMode; } public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor, IDestination destination) : this(captureMode, captureMouseCursor) { - capture.CaptureDetails.AddDestination(destination); + _capture.CaptureDetails.AddDestination(destination); } public WindowDetails SelectedCaptureWindow { get { - return selectedCaptureWindow; + return _selectedCaptureWindow; } set { - selectedCaptureWindow = value; + _selectedCaptureWindow = value; } } @@ -180,7 +176,7 @@ namespace Greenshot.Helpers { /// /// filename private void MakeCapture(string filename) { - capture.CaptureDetails.Filename = filename; + _capture.CaptureDetails.Filename = filename; MakeCapture(); } @@ -189,7 +185,7 @@ namespace Greenshot.Helpers { /// /// filename private void MakeCapture(Rectangle region) { - captureRect = region; + _captureRect = region; MakeCapture(); } @@ -211,25 +207,25 @@ namespace Greenshot.Helpers { MainForm.Instance.NotifyIcon.Visible = false; MainForm.Instance.NotifyIcon.Visible = true; } - LOG.Debug(String.Format("Capturing with mode {0} and using Cursor {1}", captureMode, captureMouseCursor)); - capture.CaptureDetails.CaptureMode = captureMode; + LOG.Debug(String.Format("Capturing with mode {0} and using Cursor {1}", _captureMode, _captureMouseCursor)); + _capture.CaptureDetails.CaptureMode = _captureMode; // Get the windows details in a seperate thread, only for those captures that have a Feedback // As currently the "elements" aren't used, we don't need them yet - switch (captureMode) { + switch (_captureMode) { case CaptureMode.Region: // Check if a region is pre-supplied! - if (Rectangle.Empty.Equals(captureRect)) { - windowDetailsThread = PrepareForCaptureWithFeedback(); + if (Rectangle.Empty.Equals(_captureRect)) { + PrepareForCaptureWithFeedback(); } break; case CaptureMode.Window: - windowDetailsThread = PrepareForCaptureWithFeedback(); + PrepareForCaptureWithFeedback(); break; } // Add destinations if no-one passed a handler - if (capture.CaptureDetails.CaptureDestinations == null || capture.CaptureDetails.CaptureDestinations.Count == 0) { + if (_capture.CaptureDetails.CaptureDestinations == null || _capture.CaptureDetails.CaptureDestinations.Count == 0) { AddConfiguredDestination(); } @@ -237,8 +233,8 @@ namespace Greenshot.Helpers { WindowDetails previouslyActiveWindow = WindowDetails.GetActiveWindow(); // Workaround for changed DPI settings in Windows 7 using (Graphics graphics = Graphics.FromHwnd(MainForm.Instance.Handle)) { - capture.CaptureDetails.DpiX = graphics.DpiX; - capture.CaptureDetails.DpiY = graphics.DpiY; + _capture.CaptureDetails.DpiX = graphics.DpiX; + _capture.CaptureDetails.DpiY = graphics.DpiY; } if (previouslyActiveWindow != null) { // Set previouslyActiveWindow as foreground window @@ -247,25 +243,25 @@ namespace Greenshot.Helpers { // Delay for the Context menu if (conf.CaptureDelay > 0) { - System.Threading.Thread.Sleep(conf.CaptureDelay); + Thread.Sleep(conf.CaptureDelay); } else { conf.CaptureDelay = 0; } // Capture Mousecursor if we are not loading from file or clipboard, only show when needed - if (captureMode != CaptureMode.File && captureMode != CaptureMode.Clipboard) { - capture = WindowCapture.CaptureCursor(capture); - if (captureMouseCursor) { - capture.CursorVisible = conf.CaptureMousepointer; + if (_captureMode != CaptureMode.File && _captureMode != CaptureMode.Clipboard) { + _capture = WindowCapture.CaptureCursor(_capture); + if (_captureMouseCursor) { + _capture.CursorVisible = conf.CaptureMousepointer; } else { - capture.CursorVisible = false; + _capture.CursorVisible = false; } } - switch(captureMode) { + switch(_captureMode) { case CaptureMode.Window: - capture = WindowCapture.CaptureScreen(capture); - capture.CaptureDetails.AddMetaData("source", "Screen"); + _capture = WindowCapture.CaptureScreen(_capture); + _capture.CaptureDetails.AddMetaData("source", "Screen"); CaptureWithFeedback(); break; case CaptureMode.ActiveWindow: @@ -277,31 +273,31 @@ namespace Greenshot.Helpers { //capture.MoveElements(capture.ScreenBounds.Location.X-capture.Location.X, capture.ScreenBounds.Location.Y-capture.Location.Y); // Capture worked, offset mouse according to screen bounds and capture location - capture.MoveMouseLocation(capture.ScreenBounds.Location.X-capture.Location.X, capture.ScreenBounds.Location.Y-capture.Location.Y); - capture.CaptureDetails.AddMetaData("source", "Window"); + _capture.MoveMouseLocation(_capture.ScreenBounds.Location.X-_capture.Location.X, _capture.ScreenBounds.Location.Y-_capture.Location.Y); + _capture.CaptureDetails.AddMetaData("source", "Window"); } else { - captureMode = CaptureMode.FullScreen; - capture = WindowCapture.CaptureScreen(capture); - capture.CaptureDetails.AddMetaData("source", "Screen"); - capture.CaptureDetails.Title = "Screen"; + _captureMode = CaptureMode.FullScreen; + _capture = WindowCapture.CaptureScreen(_capture); + _capture.CaptureDetails.AddMetaData("source", "Screen"); + _capture.CaptureDetails.Title = "Screen"; } HandleCapture(); break; case CaptureMode.IE: - if (IECaptureHelper.CaptureIE(capture, SelectedCaptureWindow) != null) { - capture.CaptureDetails.AddMetaData("source", "Internet Explorer"); + if (IECaptureHelper.CaptureIE(_capture, SelectedCaptureWindow) != null) { + _capture.CaptureDetails.AddMetaData("source", "Internet Explorer"); HandleCapture(); } break; case CaptureMode.FullScreen: // Check how we need to capture the screen bool captureTaken = false; - switch (screenCaptureMode) { + switch (_screenCaptureMode) { case ScreenCaptureMode.Auto: Point mouseLocation = WindowCapture.GetCursorLocation(); foreach (Screen screen in Screen.AllScreens) { if (screen.Bounds.Contains(mouseLocation)) { - capture = WindowCapture.CaptureRectangle(capture, screen.Bounds); + _capture = WindowCapture.CaptureRectangle(_capture, screen.Bounds); captureTaken = true; break; } @@ -309,7 +305,7 @@ namespace Greenshot.Helpers { break; case ScreenCaptureMode.Fixed: if (conf.ScreenToCapture > 0 && conf.ScreenToCapture <= Screen.AllScreens.Length) { - capture = WindowCapture.CaptureRectangle(capture, Screen.AllScreens[conf.ScreenToCapture].Bounds); + _capture = WindowCapture.CaptureRectangle(_capture, Screen.AllScreens[conf.ScreenToCapture].Bounds); captureTaken = true; } break; @@ -318,28 +314,28 @@ namespace Greenshot.Helpers { break; } if (!captureTaken) { - capture = WindowCapture.CaptureScreen(capture); + _capture = WindowCapture.CaptureScreen(_capture); } HandleCapture(); break; case CaptureMode.Clipboard: Image clipboardImage = ClipboardHelper.GetImage(); if (clipboardImage != null) { - if (capture != null) { - capture.Image = clipboardImage; + if (_capture != null) { + _capture.Image = clipboardImage; } else { - capture = new Capture(clipboardImage); + _capture = new Capture(clipboardImage); } - capture.CaptureDetails.Title = "Clipboard"; - capture.CaptureDetails.AddMetaData("source", "Clipboard"); + _capture.CaptureDetails.Title = "Clipboard"; + _capture.CaptureDetails.AddMetaData("source", "Clipboard"); // Force Editor, keep picker - if (capture.CaptureDetails.HasDestination(Destinations.PickerDestination.DESIGNATION)) { - capture.CaptureDetails.ClearDestinations(); - capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(Destinations.EditorDestination.DESIGNATION)); - capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(Destinations.PickerDestination.DESIGNATION)); + if (_capture.CaptureDetails.HasDestination(PickerDestination.DESIGNATION)) { + _capture.CaptureDetails.ClearDestinations(); + _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); + _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(PickerDestination.DESIGNATION)); } else { - capture.CaptureDetails.ClearDestinations(); - capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(Destinations.EditorDestination.DESIGNATION)); + _capture.CaptureDetails.ClearDestinations(); + _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); } HandleCapture(); } else { @@ -348,15 +344,15 @@ namespace Greenshot.Helpers { break; case CaptureMode.File: Image fileImage = null; - string filename = capture.CaptureDetails.Filename; + string filename = _capture.CaptureDetails.Filename; if (!string.IsNullOrEmpty(filename)) { try { if (filename.ToLower().EndsWith("." + OutputFormat.greenshot)) { ISurface surface = new Surface(); surface = ImageOutput.LoadGreenshotSurface(filename, surface); - surface.CaptureDetails = capture.CaptureDetails; - DestinationHelper.GetDestination(EditorDestination.DESIGNATION).ExportCapture(true, surface, capture.CaptureDetails); + surface.CaptureDetails = _capture.CaptureDetails; + DestinationHelper.GetDestination(EditorDestination.DESIGNATION).ExportCapture(true, surface, _capture.CaptureDetails); break; } } catch (Exception e) { @@ -371,29 +367,29 @@ namespace Greenshot.Helpers { } } if (fileImage != null) { - capture.CaptureDetails.Title = Path.GetFileNameWithoutExtension(filename); - capture.CaptureDetails.AddMetaData("file", filename); - capture.CaptureDetails.AddMetaData("source", "file"); - if (capture != null) { - capture.Image = fileImage; + _capture.CaptureDetails.Title = Path.GetFileNameWithoutExtension(filename); + _capture.CaptureDetails.AddMetaData("file", filename); + _capture.CaptureDetails.AddMetaData("source", "file"); + if (_capture != null) { + _capture.Image = fileImage; } else { - capture = new Capture(fileImage); + _capture = new Capture(fileImage); } // Force Editor, keep picker, this is currently the only usefull destination - if (capture.CaptureDetails.HasDestination(PickerDestination.DESIGNATION)) { - capture.CaptureDetails.ClearDestinations(); - capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); - capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(PickerDestination.DESIGNATION)); + if (_capture.CaptureDetails.HasDestination(PickerDestination.DESIGNATION)) { + _capture.CaptureDetails.ClearDestinations(); + _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); + _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(PickerDestination.DESIGNATION)); } else { - capture.CaptureDetails.ClearDestinations(); - capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); + _capture.CaptureDetails.ClearDestinations(); + _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); } HandleCapture(); } break; case CaptureMode.LastRegion: if (!RuntimeConfig.LastCapturedRegion.IsEmpty) { - capture = WindowCapture.CaptureRectangle(capture, RuntimeConfig.LastCapturedRegion); + _capture = WindowCapture.CaptureRectangle(_capture, RuntimeConfig.LastCapturedRegion); // TODO: Reactive / check if the elements code is activated //if (windowDetailsThread != null) { // windowDetailsThread.Join(); @@ -403,42 +399,42 @@ namespace Greenshot.Helpers { foreach (WindowDetails window in WindowDetails.GetVisibleWindows()) { Point estimatedLocation = new Point(RuntimeConfig.LastCapturedRegion.X + (RuntimeConfig.LastCapturedRegion.Width / 2), RuntimeConfig.LastCapturedRegion.Y + (RuntimeConfig.LastCapturedRegion.Height / 2)); if (window.Contains(estimatedLocation)) { - selectedCaptureWindow = window; - capture.CaptureDetails.Title = selectedCaptureWindow.Text; + _selectedCaptureWindow = window; + _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; break; } } // Move cursor, fixing bug #3569703 - capture.MoveMouseLocation(capture.ScreenBounds.Location.X - capture.Location.X, capture.ScreenBounds.Location.Y - capture.Location.Y); + _capture.MoveMouseLocation(_capture.ScreenBounds.Location.X - _capture.Location.X, _capture.ScreenBounds.Location.Y - _capture.Location.Y); //capture.MoveElements(capture.ScreenBounds.Location.X - capture.Location.X, capture.ScreenBounds.Location.Y - capture.Location.Y); - capture.CaptureDetails.AddMetaData("source", "screen"); + _capture.CaptureDetails.AddMetaData("source", "screen"); HandleCapture(); } break; case CaptureMode.Region: // Check if a region is pre-supplied! - if (Rectangle.Empty.Equals(captureRect)) { - capture = WindowCapture.CaptureScreen(capture); - capture.CaptureDetails.AddMetaData("source", "screen"); + if (Rectangle.Empty.Equals(_captureRect)) { + _capture = WindowCapture.CaptureScreen(_capture); + _capture.CaptureDetails.AddMetaData("source", "screen"); CaptureWithFeedback(); } else { - capture = WindowCapture.CaptureRectangle(capture, captureRect); - capture.CaptureDetails.AddMetaData("source", "screen"); + _capture = WindowCapture.CaptureRectangle(_capture, _captureRect); + _capture.CaptureDetails.AddMetaData("source", "screen"); HandleCapture(); } break; default: - LOG.Warn("Unknown capture mode: " + captureMode); + LOG.Warn("Unknown capture mode: " + _captureMode); break; } // TODO: Reactive / check if the elements code is activated //if (windowDetailsThread != null) { // windowDetailsThread.Join(); //} - if (capture != null) { + if (_capture != null) { LOG.Debug("Disposing capture"); - capture.Dispose(); + _capture.Dispose(); } } @@ -446,12 +442,12 @@ namespace Greenshot.Helpers { /// Pre-Initialization for CaptureWithFeedback, this will get all the windows before we change anything /// private Thread PrepareForCaptureWithFeedback() { - windows = new List(); + _windows = new List(); // If the App Launcher is visisble, no other windows are active WindowDetails appLauncherWindow = WindowDetails.GetAppLauncher(); if (appLauncherWindow != null && appLauncherWindow.Visible) { - windows.Add(appLauncherWindow); + _windows.Add(appLauncherWindow); return null; } @@ -481,8 +477,8 @@ namespace Greenshot.Helpers { goLevelDeep = 20; } window.GetChildren(goLevelDeep); - lock (windows) { - windows.Add(window); + lock (_windows) { + _windows.Add(window); } // TODO: Following code should be enabled & checked if the editor can support "elements" @@ -535,7 +531,7 @@ namespace Greenshot.Helpers { foreach(string destinationDesignation in conf.OutputDestinations) { IDestination destination = DestinationHelper.GetDestination(destinationDesignation); if (destination != null) { - capture.CaptureDetails.AddDestination(destination); + _capture.CaptureDetails.AddDestination(destination); } } } @@ -546,26 +542,26 @@ namespace Greenshot.Helpers { bool outputMade = false; // Make sure the user sees that the capture is made - if (capture.CaptureDetails.CaptureMode == CaptureMode.File || capture.CaptureDetails.CaptureMode == CaptureMode.Clipboard) { + if (_capture.CaptureDetails.CaptureMode == CaptureMode.File || _capture.CaptureDetails.CaptureMode == CaptureMode.Clipboard) { // Maybe not "made" but the original is still there... somehow outputMade = true; } else { // Make sure the resolution is set correctly! - if (capture.CaptureDetails != null && capture.Image != null) { - ((Bitmap)capture.Image).SetResolution(capture.CaptureDetails.DpiX, capture.CaptureDetails.DpiY); + if (_capture.CaptureDetails != null && _capture.Image != null) { + ((Bitmap)_capture.Image).SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); } DoCaptureFeedback(); } - LOG.Debug("A capture of: " + capture.CaptureDetails.Title); + LOG.Debug("A capture of: " + _capture.CaptureDetails.Title); // check if someone has passed a destination - if (capture.CaptureDetails.CaptureDestinations == null || capture.CaptureDetails.CaptureDestinations.Count == 0) { + if (_capture.CaptureDetails.CaptureDestinations == null || _capture.CaptureDetails.CaptureDestinations.Count == 0) { AddConfiguredDestination(); } // Create Surface with capture, this way elements can be added automatically (like the mouse cursor) - Surface surface = new Surface(capture); + Surface surface = new Surface(_capture); surface.Modified = !outputMade; // Register notify events if this is wanted @@ -629,7 +625,7 @@ namespace Greenshot.Helpers { } } else { if (!string.IsNullOrEmpty(surface.UploadURL)) { - System.Diagnostics.Process.Start(surface.UploadURL); + Process.Start(surface.UploadURL); } } LOG.DebugFormat("Deregistering the BalloonTipClicked"); @@ -648,28 +644,28 @@ namespace Greenshot.Helpers { foreach(IProcessor processor in ProcessorHelper.GetAllProcessors()) { if (processor.isActive) { LOG.InfoFormat("Calling processor {0}", processor.Description); - processor.ProcessCapture(surface, capture.CaptureDetails); + processor.ProcessCapture(surface, _capture.CaptureDetails); } } // As the surfaces copies the reference to the image, make sure the image is not being disposed (a trick to save memory) - capture.Image = null; + _capture.Image = null; // Get CaptureDetails as we need it even after the capture is disposed - ICaptureDetails captureDetails = capture.CaptureDetails; + ICaptureDetails captureDetails = _capture.CaptureDetails; bool canDisposeSurface = true; - if (captureDetails.HasDestination(Destinations.PickerDestination.DESIGNATION)) { - DestinationHelper.ExportCapture(false, Destinations.PickerDestination.DESIGNATION, surface, captureDetails); + if (captureDetails.HasDestination(PickerDestination.DESIGNATION)) { + DestinationHelper.ExportCapture(false, PickerDestination.DESIGNATION, surface, captureDetails); captureDetails.CaptureDestinations.Clear(); canDisposeSurface = false; } // Disable capturing - captureMode = CaptureMode.None; + _captureMode = CaptureMode.None; // Dispose the capture, we don't need it anymore (the surface copied all information and we got the title (if any)). - capture.Dispose(); - capture = null; + _capture.Dispose(); + _capture = null; int destinationCount = captureDetails.CaptureDestinations.Count; if (destinationCount > 0) { @@ -682,7 +678,7 @@ namespace Greenshot.Helpers { LOG.InfoFormat("Calling destination {0}", destination.Description); ExportInformation exportInformation = destination.ExportCapture(false, surface, captureDetails); - if (Destinations.EditorDestination.DESIGNATION.Equals(destination.Designation) && exportInformation.ExportMade) { + if (EditorDestination.DESIGNATION.Equals(destination.Designation) && exportInformation.ExportMade) { canDisposeSurface = false; } } @@ -695,34 +691,34 @@ namespace Greenshot.Helpers { private bool CaptureActiveWindow() { bool presupplied = false; LOG.Debug("CaptureActiveWindow"); - if (selectedCaptureWindow != null) { + if (_selectedCaptureWindow != null) { LOG.Debug("Using supplied window"); presupplied = true; } else { - selectedCaptureWindow = WindowDetails.GetActiveWindow(); - if (selectedCaptureWindow != null) { - LOG.DebugFormat("Capturing window: {0} with {1}", selectedCaptureWindow.Text, selectedCaptureWindow.WindowRectangle); + _selectedCaptureWindow = WindowDetails.GetActiveWindow(); + if (_selectedCaptureWindow != null) { + LOG.DebugFormat("Capturing window: {0} with {1}", _selectedCaptureWindow.Text, _selectedCaptureWindow.WindowRectangle); } } - if (selectedCaptureWindow == null || (!presupplied && selectedCaptureWindow.Iconic)) { + if (_selectedCaptureWindow == null || (!presupplied && _selectedCaptureWindow.Iconic)) { LOG.Warn("No window to capture!"); // Nothing to capture, code up in the stack will capture the full screen return false; } - if (!presupplied && selectedCaptureWindow != null && selectedCaptureWindow.Iconic) { + if (!presupplied && _selectedCaptureWindow != null && _selectedCaptureWindow.Iconic) { // Restore the window making sure it's visible! // This is done mainly for a screen capture, but some applications like Excel and TOAD have weird behaviour! - selectedCaptureWindow.Restore(); + _selectedCaptureWindow.Restore(); } - selectedCaptureWindow = SelectCaptureWindow(selectedCaptureWindow); - if (selectedCaptureWindow == null) { + _selectedCaptureWindow = SelectCaptureWindow(_selectedCaptureWindow); + if (_selectedCaptureWindow == null) { LOG.Warn("No window to capture, after SelectCaptureWindow!"); // Nothing to capture, code up in the stack will capture the full screen return false; } // Fix for Bug #3430560 - RuntimeConfig.LastCapturedRegion = selectedCaptureWindow.WindowRectangle; - bool returnValue = CaptureWindow(selectedCaptureWindow, capture, conf.WindowCaptureMode) != null; + RuntimeConfig.LastCapturedRegion = _selectedCaptureWindow.WindowRectangle; + bool returnValue = CaptureWindow(_selectedCaptureWindow, _capture, conf.WindowCaptureMode) != null; return returnValue; } @@ -954,17 +950,17 @@ namespace Greenshot.Helpers { app.HideApp(); } } - using (CaptureForm captureForm = new CaptureForm(capture, windows)) { + using (CaptureForm captureForm = new CaptureForm(_capture, _windows)) { DialogResult result = captureForm.ShowDialog(); if (result == DialogResult.OK) { - selectedCaptureWindow = captureForm.SelectedCaptureWindow; - captureRect = captureForm.CaptureRectangle; + _selectedCaptureWindow = captureForm.SelectedCaptureWindow; + _captureRect = captureForm.CaptureRectangle; // Get title - if (selectedCaptureWindow != null) { - capture.CaptureDetails.Title = selectedCaptureWindow.Text; + if (_selectedCaptureWindow != null) { + _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; } - if (captureRect.Height > 0 && captureRect.Width > 0) { + if (_captureRect.Height > 0 && _captureRect.Width > 0) { // TODO: Reactive / check if the elements code is activated //if (windowDetailsThread != null) { // windowDetailsThread.Join(); @@ -990,12 +986,12 @@ namespace Greenshot.Helpers { // } //} // Take the captureRect, this already is specified as bitmap coordinates - capture.Crop(captureRect); + _capture.Crop(_captureRect); // save for re-capturing later and show recapture context menu option // Important here is that the location needs to be offsetted back to screen coordinates! - Rectangle tmpRectangle = captureRect.Clone(); - tmpRectangle.Offset(capture.ScreenBounds.Location.X, capture.ScreenBounds.Location.Y); + Rectangle tmpRectangle = _captureRect; + tmpRectangle.Offset(_capture.ScreenBounds.Location.X, _capture.ScreenBounds.Location.Y); RuntimeConfig.LastCapturedRegion = tmpRectangle; HandleCapture(); } diff --git a/Greenshot/Helpers/Colors.cs b/Greenshot/Helpers/Colors.cs index 8a0de4de3..0f3f3e53f 100644 --- a/Greenshot/Helpers/Colors.cs +++ b/Greenshot/Helpers/Colors.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.Drawing; diff --git a/Greenshot/Helpers/CopyData.cs b/Greenshot/Helpers/CopyData.cs index 3b3e393af..99d9628cf 100644 --- a/Greenshot/Helpers/CopyData.cs +++ b/Greenshot/Helpers/CopyData.cs @@ -42,7 +42,7 @@ namespace Greenshot.Helpers { get {return commands;} } public CopyDataTransport() { - this.commands = new List>(); + commands = new List>(); } public CopyDataTransport(CommandEnum command) : this() { @@ -53,10 +53,10 @@ namespace Greenshot.Helpers { AddCommand(command, commandData); } public void AddCommand(CommandEnum command) { - this.commands.Add(new KeyValuePair(command, null)); + commands.Add(new KeyValuePair(command, null)); } public void AddCommand(CommandEnum command, string commandData) { - this.commands.Add(new KeyValuePair(command, commandData)); + commands.Add(new KeyValuePair(command, commandData)); } } @@ -98,7 +98,7 @@ namespace Greenshot.Helpers { /// messages sent by other instances of this class. /// /// The Windows Message information. - protected override void WndProc (ref System.Windows.Forms.Message m ) { + protected override void WndProc (ref Message m ) { if (m.Msg == WM_COPYDATA) { COPYDATASTRUCT cds = new COPYDATASTRUCT(); cds = (COPYDATASTRUCT) Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); @@ -151,7 +151,7 @@ namespace Greenshot.Helpers { /// public CopyDataChannels Channels { get { - return this.channels; + return channels; } } @@ -202,7 +202,7 @@ namespace Greenshot.Helpers { /// public string ChannelName { get { - return this.channelName; + return channelName; } } /// @@ -210,7 +210,7 @@ namespace Greenshot.Helpers { /// public Object Data { get { - return this.data; + return data; } } /// @@ -219,7 +219,7 @@ namespace Greenshot.Helpers { /// public DateTime Sent { get { - return this.sent; + return sent; } } /// @@ -228,7 +228,7 @@ namespace Greenshot.Helpers { /// public DateTime Received { get { - return this.received; + return received; } } /// @@ -241,7 +241,7 @@ namespace Greenshot.Helpers { this.channelName = channelName; this.data = data; this.sent = sent; - this.received = DateTime.Now; + received = DateTime.Now; } } @@ -258,8 +258,8 @@ namespace Greenshot.Helpers { /// /// An enumerator for each of the CopyDataChannel objects /// within this collection. - public new System.Collections.IEnumerator GetEnumerator ( ) { - return this.Dictionary.Values.GetEnumerator(); + public new IEnumerator GetEnumerator ( ) { + return Dictionary.Values.GetEnumerator(); } /// @@ -269,7 +269,7 @@ namespace Greenshot.Helpers { get { CopyDataChannel ret = null; int i = 0; - foreach (CopyDataChannel cdc in this.Dictionary.Values) { + foreach (CopyDataChannel cdc in Dictionary.Values) { i++; if (i == index) { ret = cdc; @@ -284,7 +284,7 @@ namespace Greenshot.Helpers { /// public CopyDataChannel this[string channelName] { get { - return (CopyDataChannel) this.Dictionary[channelName]; + return (CopyDataChannel) Dictionary[channelName]; } } /// @@ -293,21 +293,21 @@ namespace Greenshot.Helpers { /// public void Add(string channelName) { CopyDataChannel cdc = new CopyDataChannel(owner, channelName); - this.Dictionary.Add(channelName , cdc); + Dictionary.Add(channelName , cdc); } /// /// Removes an existing channel. /// /// The channel to remove public void Remove(string channelName) { - this.Dictionary.Remove(channelName); + Dictionary.Remove(channelName); } /// /// Gets/sets whether this channel contains a CopyDataChannel /// for the specified channelName. /// public bool Contains(string channelName) { - return this.Dictionary.Contains(channelName); + return Dictionary.Contains(channelName); } /// @@ -315,7 +315,7 @@ namespace Greenshot.Helpers { /// object collected by this class are cleared up. /// protected override void OnClear() { - foreach (CopyDataChannel cdc in this.Dictionary.Values) { + foreach (CopyDataChannel cdc in Dictionary.Values) { cdc.Dispose(); } base.OnClear(); @@ -328,7 +328,7 @@ namespace Greenshot.Helpers { /// The channelName /// The CopyDataChannel object which has /// just been removed - protected override void OnRemoveComplete ( Object key , System.Object data ) { + protected override void OnRemoveComplete ( Object key , Object data ) { ( (CopyDataChannel) data).Dispose(); base.OnRemove(key, data); } @@ -341,7 +341,7 @@ namespace Greenshot.Helpers { /// the new handle has been assigned. /// public void OnHandleChange() { - foreach (CopyDataChannel cdc in this.Dictionary.Values) { + foreach (CopyDataChannel cdc in Dictionary.Values) { cdc.OnHandleChange(); } } @@ -393,7 +393,7 @@ namespace Greenshot.Helpers { /// public string ChannelName { get { - return this.channelName; + return channelName; } } @@ -442,8 +442,8 @@ namespace Greenshot.Helpers { // Send the data to each window identified on // the channel: foreach(WindowDetails window in WindowDetails.GetAllWindows()) { - if (!window.Handle.Equals(this.owner.Handle)) { - if (GetProp(window.Handle, this.channelName) != IntPtr.Zero) { + if (!window.Handle.Equals(owner.Handle)) { + if (GetProp(window.Handle, channelName) != IntPtr.Zero) { COPYDATASTRUCT cds = new COPYDATASTRUCT(); cds.cbData = dataSize; cds.dwData = IntPtr.Zero; @@ -464,12 +464,12 @@ namespace Greenshot.Helpers { private void addChannel() { // Tag this window with property "channelName" - SetProp(owner.Handle, this.channelName, (int)owner.Handle); + SetProp(owner.Handle, channelName, (int)owner.Handle); } private void removeChannel() { // Remove the "channelName" property from this window - RemoveProp(owner.Handle, this.channelName); + RemoveProp(owner.Handle, channelName); } /// diff --git a/Greenshot/Helpers/DestinationHelper.cs b/Greenshot/Helpers/DestinationHelper.cs index cac26471b..2f83b9ccb 100644 --- a/Greenshot/Helpers/DestinationHelper.cs +++ b/Greenshot/Helpers/DestinationHelper.cs @@ -23,15 +23,15 @@ using System.Collections.Generic; using Greenshot.Plugin; using GreenshotPlugin.Core; -using Greenshot.Destinations; using Greenshot.IniFile; +using log4net; namespace Greenshot.Helpers { /// /// Description of DestinationHelper. /// public static class DestinationHelper { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(DestinationHelper)); + private static ILog LOG = LogManager.GetLogger(typeof(DestinationHelper)); private static Dictionary RegisteredDestinations = new Dictionary(); private static CoreConfiguration coreConfig = IniConfig.GetIniSection(); diff --git a/Greenshot/Helpers/EnvironmentInfo.cs b/Greenshot/Helpers/EnvironmentInfo.cs index 95aecb11d..c9399850a 100644 --- a/Greenshot/Helpers/EnvironmentInfo.cs +++ b/Greenshot/Helpers/EnvironmentInfo.cs @@ -29,13 +29,14 @@ using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.Core; using Greenshot.IniFile; using Greenshot.Drawing; +using log4net; namespace Greenshot.Helpers { /// /// Description of EnvironmentInfo. /// public static class EnvironmentInfo { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(EnvironmentInfo)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(EnvironmentInfo)); private static bool? isWindows = null; public static bool IsWindows { @@ -157,8 +158,8 @@ namespace Greenshot.Helpers { public static string BuildReport(Exception exception) { StringBuilder exceptionText = new StringBuilder(); - exceptionText.AppendLine(EnvironmentInfo.EnvironmentToString(true)); - exceptionText.AppendLine(EnvironmentInfo.ExceptionToString(exception)); + exceptionText.AppendLine(EnvironmentToString(true)); + exceptionText.AppendLine(ExceptionToString(exception)); exceptionText.AppendLine("Configuration dump:"); using (TextWriter writer = new StringWriter(exceptionText)) { IniConfig.GetIniSection().Write(writer, true); diff --git a/Greenshot/Helpers/GuiRectangle.cs b/Greenshot/Helpers/GuiRectangle.cs index efd65b41e..a23f105b3 100644 --- a/Greenshot/Helpers/GuiRectangle.cs +++ b/Greenshot/Helpers/GuiRectangle.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.Drawing; namespace Greenshot.Helpers { diff --git a/Greenshot/Helpers/HookHelper.cs b/Greenshot/Helpers/HookHelper.cs index a74da7ee8..ca261a870 100644 --- a/Greenshot/Helpers/HookHelper.cs +++ b/Greenshot/Helpers/HookHelper.cs @@ -20,9 +20,7 @@ */ using System; using System.Collections.Generic; -using System.Text; using GreenshotPlugin.UnmanagedHelpers; -using System.Diagnostics; using GreenshotPlugin.Core; namespace Greenshot.Helpers { diff --git a/Greenshot/Helpers/IECaptureHelper.cs b/Greenshot/Helpers/IECaptureHelper.cs index c2176ba0a..1284faa80 100644 --- a/Greenshot/Helpers/IECaptureHelper.cs +++ b/Greenshot/Helpers/IECaptureHelper.cs @@ -22,9 +22,8 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; - +using System.Runtime.InteropServices; using Greenshot.Configuration; -using Greenshot.Drawing.Filters; using Greenshot.Helpers.IEInterop; using Greenshot.Interop; using Greenshot.Interop.IE; @@ -33,6 +32,7 @@ using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.Controls; using GreenshotPlugin.Core; using Greenshot.IniFile; +using log4net; namespace Greenshot.Helpers { /// @@ -42,7 +42,7 @@ namespace Greenshot.Helpers { /// Many thanks to all the people who contributed here! /// public static class IECaptureHelper { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IECaptureHelper)); + private static ILog LOG = LogManager.GetLogger(typeof(IECaptureHelper)); private static CoreConfiguration configuration = IniConfig.GetIniSection(); // Helper method to activate a certain IE Tab @@ -145,7 +145,7 @@ namespace Greenshot.Helpers { try { IHTMLDocument2 document2 = getHTMLDocument(ieWindow); string title = document2.title; - System.Runtime.InteropServices.Marshal.ReleaseComObject(document2); + Marshal.ReleaseComObject(document2); if (string.IsNullOrEmpty(title)) { singleWindowText.Add(ieWindow.Text); } else { diff --git a/Greenshot/Helpers/IEInterop/IEContainer.cs b/Greenshot/Helpers/IEInterop/IEContainer.cs index 52ec63d9f..0ba19a4df 100644 --- a/Greenshot/Helpers/IEInterop/IEContainer.cs +++ b/Greenshot/Helpers/IEInterop/IEContainer.cs @@ -25,14 +25,14 @@ using System.Globalization; using System.Runtime.InteropServices; using GreenshotPlugin.Core; -using Greenshot.Plugin; -using Greenshot.Interop; using Greenshot.Interop.IE; using Greenshot.IniFile; +using log4net; +using IServiceProvider = Greenshot.Interop.IServiceProvider; namespace Greenshot.Helpers.IEInterop { public class DocumentContainer { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(DocumentContainer)); + private static ILog LOG = LogManager.GetLogger(typeof(DocumentContainer)); private static CoreConfiguration configuration = IniConfig.GetIniSection(); private const int E_ACCESSDENIED = unchecked((int)0x80070005L); private static readonly Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046"); @@ -114,7 +114,7 @@ namespace Greenshot.Helpers.IEInterop { private void Init(IHTMLDocument2 document2, WindowDetails contentWindow) { this.document2 = document2; this.contentWindow = contentWindow; - this.document3 = document2 as IHTMLDocument3; + document3 = document2 as IHTMLDocument3; // Check what access method is needed for the document IHTMLDocument5 document5 = (IHTMLDocument5)document2; @@ -298,7 +298,7 @@ namespace Greenshot.Helpers.IEInterop { LOG.Warn("comEx.ErrorCode != E_ACCESSDENIED but", comEx); return null; } - } catch (System.UnauthorizedAccessException) { + } catch (UnauthorizedAccessException) { // This error is okay, ignoring it } catch (Exception ex1) { LOG.Warn("Some error: ", ex1); @@ -310,12 +310,12 @@ namespace Greenshot.Helpers.IEInterop { // IE tries to prevent a cross frame scripting security issue. try { // Convert IHTMLWindow2 to IWebBrowser2 using IServiceProvider. - Interop.IServiceProvider sp = (Interop.IServiceProvider)htmlWindow; + IServiceProvider sp = (IServiceProvider)htmlWindow; // Use IServiceProvider.QueryService to get IWebBrowser2 object. Object brws = null; - Guid webBrowserApp = IID_IWebBrowserApp.Clone(); - Guid webBrowser2 = IID_IWebBrowser2.Clone(); + Guid webBrowserApp = IID_IWebBrowserApp; + Guid webBrowser2 = IID_IWebBrowser2; sp.QueryService(ref webBrowserApp, ref webBrowser2, out brws); // Get the document from IWebBrowser2. @@ -543,7 +543,7 @@ namespace Greenshot.Helpers.IEInterop { public Rectangle DestinationRectangle { get { - return new Rectangle(this.DestinationLocation, this.DestinationSize); + return new Rectangle(DestinationLocation, DestinationSize); } } diff --git a/Greenshot/Helpers/MailHelper.cs b/Greenshot/Helpers/MailHelper.cs index 74838d5b0..e5fad7bc2 100644 --- a/Greenshot/Helpers/MailHelper.cs +++ b/Greenshot/Helpers/MailHelper.cs @@ -21,22 +21,21 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Drawing; using System.IO; using System.Runtime.InteropServices; -using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using Greenshot.Plugin; using GreenshotPlugin.Core; using Greenshot.IniFile; - /// /// Author: Andrew Baker /// Datum: 10.03.2006 /// Available from: http://www.vbusers.com/codecsharp/codeget.asp?ThreadID=71&PostID=1 /// +using log4net; + namespace Greenshot.Helpers { #region Public MapiMailMessage Class @@ -44,7 +43,7 @@ namespace Greenshot.Helpers { /// Represents an email message to be sent through MAPI. /// public class MapiMailMessage { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(MapiMailMessage)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(MapiMailMessage)); private static CoreConfiguration conf = IniConfig.GetIniSection(); /// @@ -220,7 +219,7 @@ namespace Greenshot.Helpers { /// public void ShowDialog() { // Create the mail message in an STA thread - Thread t = new Thread(new ThreadStart(_ShowMail)); + Thread t = new Thread(_ShowMail); t.IsBackground = true; t.Name = "Create MAPI mail"; t.SetApartmentState(ApartmentState.STA); @@ -291,7 +290,7 @@ namespace Greenshot.Helpers { int fsize = Marshal.SizeOf(fileDescType); // Get the ptr to the files - IntPtr runptr = message.Files.Clone(); + IntPtr runptr = message.Files; // Release each file for (int i = 0; i < message.FileCount; i++) { Marshal.DestroyStructure(runptr, fileDescType); @@ -322,7 +321,7 @@ namespace Greenshot.Helpers { MapiFileDescriptor mfd = new MapiFileDescriptor(); mfd.position = -1; - IntPtr runptr = ptra.Clone(); + IntPtr runptr = ptra; for (int i = 0; i < _files.Count; i++) { string path = _files[i] as string; mfd.name = Path.GetFileName(path); @@ -620,28 +619,28 @@ namespace Greenshot.Helpers { /// Adds a new recipient with the specified address to this collection. /// public void Add(string address) { - this.Add(new Recipient(address)); + Add(new Recipient(address)); } /// /// Adds a new recipient with the specified address and display name to this collection. /// public void Add(string address, string displayName) { - this.Add(new Recipient(address, displayName)); + Add(new Recipient(address, displayName)); } /// /// Adds a new recipient with the specified address and recipient type to this collection. /// public void Add(string address, MapiMailMessage.RecipientType recipientType) { - this.Add(new Recipient(address, recipientType)); + Add(new Recipient(address, recipientType)); } /// /// Adds a new recipient with the specified address, display name and recipient type to this collection. /// public void Add(string address, string displayName, MapiMailMessage.RecipientType recipientType) { - this.Add(new Recipient(address, displayName, recipientType)); + Add(new Recipient(address, displayName, recipientType)); } /// @@ -687,7 +686,7 @@ namespace Greenshot.Helpers { _handle = Marshal.AllocHGlobal(_count * size); // place all interop recipients into the memory just allocated - IntPtr ptr = _handle.Clone(); + IntPtr ptr = _handle; foreach (Recipient native in outer) { MapiMailMessage.MAPIHelperInterop.MapiRecipDesc interop = native.GetInteropRepresentation(); @@ -720,7 +719,7 @@ namespace Greenshot.Helpers { int size = Marshal.SizeOf(type); // destroy all the structures in the memory area - IntPtr ptr = _handle.Clone(); + IntPtr ptr = _handle; for (int i = 0; i < _count; i++) { Marshal.DestroyStructure(ptr, type); ptr = new IntPtr(ptr.ToInt64() + size); diff --git a/Greenshot/Helpers/PluginHelper.cs b/Greenshot/Helpers/PluginHelper.cs index 414c32c6d..ddc443036 100644 --- a/Greenshot/Helpers/PluginHelper.cs +++ b/Greenshot/Helpers/PluginHelper.cs @@ -24,11 +24,10 @@ using System.Drawing; using System.IO; using System.Reflection; using System.Windows.Forms; - -using Greenshot.Configuration; using Greenshot.Plugin; using GreenshotPlugin.Core; using Greenshot.IniFile; +using log4net; namespace Greenshot.Helpers { /// @@ -36,7 +35,7 @@ namespace Greenshot.Helpers { /// [Serializable] public class PluginHelper : IGreenshotHost { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PluginHelper)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginHelper)); private static CoreConfiguration conf = IniConfig.GetIniSection(); private static string pluginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Application.ProductName); @@ -118,7 +117,7 @@ namespace Greenshot.Helpers { /// Image of which we need a Thumbnail /// Image with Thumbnail public Image GetThumbnail(Image image, int width, int height) { - return image.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero); + return image.GetThumbnailImage(width, height, ThumbnailCallback, IntPtr.Zero); } /// @@ -220,7 +219,7 @@ namespace Greenshot.Helpers { foreach (string pluginFile in Directory.GetFiles(path, "*.gsp", SearchOption.AllDirectories)) { pluginFiles.Add(pluginFile); } - } catch (System.UnauthorizedAccessException) { + } catch (UnauthorizedAccessException) { return; } catch (Exception ex) { LOG.Error("Error loading plugin: ", ex); diff --git a/Greenshot/Helpers/PrintHelper.cs b/Greenshot/Helpers/PrintHelper.cs index a8637c954..abbd2fd87 100644 --- a/Greenshot/Helpers/PrintHelper.cs +++ b/Greenshot/Helpers/PrintHelper.cs @@ -24,19 +24,19 @@ using System.Drawing.Printing; using System.Windows.Forms; using Greenshot.Configuration; -using Greenshot.Drawing; using Greenshot.Forms; using Greenshot.Plugin; using GreenshotPlugin.Core; using Greenshot.IniFile; using Greenshot.Core; +using log4net; namespace Greenshot.Helpers { /// /// Description of PrintHelper. /// public class PrintHelper : IDisposable { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PrintHelper)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(PrintHelper)); private static CoreConfiguration conf = IniConfig.GetIniSection(); private ISurface surface; diff --git a/Greenshot/Helpers/ProcessorHelper.cs b/Greenshot/Helpers/ProcessorHelper.cs index 9436313fa..f3af396c0 100644 --- a/Greenshot/Helpers/ProcessorHelper.cs +++ b/Greenshot/Helpers/ProcessorHelper.cs @@ -23,13 +23,14 @@ using System.Collections.Generic; using Greenshot.Plugin; using GreenshotPlugin.Core; +using log4net; namespace Greenshot.Helpers { /// /// Description of ProcessorHelper. /// public static class ProcessorHelper { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ProcessorHelper)); + private static ILog LOG = LogManager.GetLogger(typeof(ProcessorHelper)); private static Dictionary RegisteredProcessors = new Dictionary(); /// Initialize the Processors diff --git a/Greenshot/Helpers/ScaleHelper.cs b/Greenshot/Helpers/ScaleHelper.cs index 1ce044aa7..c2315da44 100644 --- a/Greenshot/Helpers/ScaleHelper.cs +++ b/Greenshot/Helpers/ScaleHelper.cs @@ -22,6 +22,7 @@ using System; using System.Drawing; using System.Windows.Forms; using Greenshot.Drawing; +using log4net; namespace Greenshot.Helpers { /// @@ -45,7 +46,7 @@ namespace Greenshot.Helpers { Rational = 0x02 } - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ScaleHelper)); + 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 @@ -289,10 +290,10 @@ namespace Greenshot.Helpers { public static void Scale(Rectangle boundsBeforeResize, int gripperPosition, int cursorX, int cursorY, ref RectangleF boundsAfterResize, IDoubleProcessor angleRoundBehavior) { - ScaleHelper.ScaleOptions opts = ScaleHelper.GetScaleOptions(); + ScaleOptions opts = GetScaleOptions(); - bool rationalScale = (opts & ScaleHelper.ScaleOptions.Rational) == ScaleHelper.ScaleOptions.Rational; - bool centeredScale = (opts & ScaleHelper.ScaleOptions.Centered) == ScaleHelper.ScaleOptions.Centered; + bool rationalScale = (opts & ScaleOptions.Rational) == ScaleOptions.Rational; + bool centeredScale = (opts & ScaleOptions.Centered) == ScaleOptions.Centered; if(rationalScale) { double angle = GeometryHelper.Angle2D(boundsBeforeResize.X, boundsBeforeResize.Y, cursorX, cursorY); @@ -320,7 +321,7 @@ namespace Greenshot.Helpers { } /// the current ScaleOptions depending on modifier keys held down - public static ScaleHelper.ScaleOptions GetScaleOptions() { + public static ScaleOptions GetScaleOptions() { bool anchorAtCenter = (Control.ModifierKeys & Keys.Control) != 0; bool maintainAspectRatio = ((Control.ModifierKeys & Keys.Shift) != 0); ScaleOptions opts = ScaleOptions.Default; @@ -353,7 +354,7 @@ namespace Greenshot.Helpers { this.fixedAngle = fixedAngle; } public double Process(double angle) { - return this.fixedAngle; + return fixedAngle; } } diff --git a/Greenshot/Helpers/ScreenCaptureHelper.cs b/Greenshot/Helpers/ScreenCaptureHelper.cs index 4336ff708..29e16ee38 100644 --- a/Greenshot/Helpers/ScreenCaptureHelper.cs +++ b/Greenshot/Helpers/ScreenCaptureHelper.cs @@ -19,20 +19,14 @@ * along with this program. If not, see . */ using System; -using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; -using System.Reflection; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; - -using Greenshot; -using Greenshot.Configuration; -using Greenshot.Plugin; using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.Core; using Greenshot.IniFile; diff --git a/Greenshot/Helpers/SoundHelper.cs b/Greenshot/Helpers/SoundHelper.cs index 6c0406cad..acd79ed69 100644 --- a/Greenshot/Helpers/SoundHelper.cs +++ b/Greenshot/Helpers/SoundHelper.cs @@ -27,17 +27,18 @@ using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.Core; using Greenshot.IniFile; using System.IO; - /// /// Create to fix the sometimes wrongly played sample, especially after first start from IDE /// See: http://www.codeproject.com/KB/audio-video/soundplayerbug.aspx?msg=2487569 /// +using log4net; + namespace Greenshot.Helpers { /// /// Description of SoundHelper. /// public static class SoundHelper { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(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; diff --git a/Greenshot/Helpers/StartupHelper.cs b/Greenshot/Helpers/StartupHelper.cs index f4185cb62..0ed7d74db 100644 --- a/Greenshot/Helpers/StartupHelper.cs +++ b/Greenshot/Helpers/StartupHelper.cs @@ -20,6 +20,7 @@ */ using System; using System.Windows.Forms; +using log4net; using Microsoft.Win32; using System.IO; @@ -28,14 +29,14 @@ namespace Greenshot.Helpers { /// A helper class for the startup registry /// public static class StartupHelper { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(StartupHelper)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(StartupHelper)); private const string RUNKEY6432 = @"Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"; private const string RUNKEY = @"Software\Microsoft\Windows\CurrentVersion\Run"; private const string APPLICATIONNAME = "Greenshot"; - private static string getExecutablePath() { + private static string GetExecutablePath() { return "\"" + Application.ExecutablePath + "\""; } @@ -43,7 +44,7 @@ namespace Greenshot.Helpers { /// Return true if the current user can write the RUN key of the local machine. /// /// true if Greenshot can write key - public static bool canWriteRunAll() { + public static bool CanWriteRunAll() { try { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RUNKEY, true)) { } @@ -57,7 +58,7 @@ namespace Greenshot.Helpers { /// Return true if the current user can write the RUN key of the current user. /// /// true if Greenshot can write key - public static bool canWriteRunUser() { + public static bool CanWriteRunUser() { try { using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY, true)) { } @@ -71,7 +72,7 @@ namespace Greenshot.Helpers { /// Return the RUN key value of the local machine /// /// the RUN key value of the local machine - public static Object getRunAllValue() { + public static Object GetRunAllValue() { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RUNKEY, false)) { if (key != null) { object runValue = key.GetValue(APPLICATIONNAME); @@ -98,7 +99,7 @@ namespace Greenshot.Helpers { /// Return the RUN key value of the current user /// /// the RUN key value of the current user - public static Object getRunUserValue() { + public static Object GetRunUserValue() { using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY, false)) { if (key != null) { object runValue = key.GetValue(APPLICATIONNAME); @@ -125,9 +126,9 @@ namespace Greenshot.Helpers { /// Return true if the local machine has a RUN entry for Greenshot /// /// true if there is a run key - public static bool hasRunAll() { + public static bool HasRunAll() { try { - return getRunAllValue() != null; + return GetRunAllValue() != null; } catch (Exception e) { LOG.Error("Error retrieving RunAllValue", e); } @@ -138,10 +139,10 @@ namespace Greenshot.Helpers { /// Return true if the current user has a RUN entry for Greenshot /// /// true if there is a run key - public static bool hasRunUser() { + public static bool HasRunUser() { Object runValue = null; try { - runValue = getRunUserValue(); + runValue = GetRunUserValue(); } catch (Exception e) { LOG.Error("Error retrieving RunUserValue", e); } @@ -151,8 +152,8 @@ namespace Greenshot.Helpers { /// /// Delete the RUN key for the localmachine ("ALL") /// - public static void deleteRunAll() { - if (hasRunAll()) { + public static void DeleteRunAll() { + if (HasRunAll()) { try { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RUNKEY, true)) { key.DeleteValue(APPLICATIONNAME); @@ -176,8 +177,8 @@ namespace Greenshot.Helpers { /// /// Delete the RUN key for the current user /// - public static void deleteRunUser() { - if (hasRunUser()) { + public static void DeleteRunUser() { + if (HasRunUser()) { try { using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY, true)) { key.DeleteValue(APPLICATIONNAME); @@ -201,10 +202,10 @@ namespace Greenshot.Helpers { /// /// Set the RUN key for the current user /// - public static void setRunUser() { + public static void SetRunUser() { try { using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY, true)) { - key.SetValue(APPLICATIONNAME, getExecutablePath()); + key.SetValue(APPLICATIONNAME, GetExecutablePath()); } } catch (Exception e) { LOG.Error("Error in setRunUser.", e); diff --git a/Greenshot/Helpers/UpdateHelper.cs b/Greenshot/Helpers/UpdateHelper.cs index 3b84f2de4..d178e035a 100644 --- a/Greenshot/Helpers/UpdateHelper.cs +++ b/Greenshot/Helpers/UpdateHelper.cs @@ -21,22 +21,20 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Globalization; -using System.Net; using System.Reflection; -using System.Text.RegularExpressions; using System.Windows.Forms; using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.IniFile; +using log4net; namespace Greenshot.Experimental { /// /// Description of RssFeedHelper. /// public static class UpdateHelper { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(UpdateHelper)); + private static ILog LOG = LogManager.GetLogger(typeof(UpdateHelper)); private static 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/"; @@ -79,7 +77,7 @@ namespace Greenshot.Experimental { try { latestGreenshot = null; - UpdateHelper.ProcessRSSInfo(currentVersion); + ProcessRSSInfo(currentVersion); if (latestGreenshot != null) { MainForm.Instance.NotifyIcon.BalloonTipClicked += HandleBalloonTipClick; MainForm.Instance.NotifyIcon.BalloonTipClosed += CleanupBalloonTipClick; diff --git a/Greenshot/Helpers/WindowWrapper.cs b/Greenshot/Helpers/WindowWrapper.cs index 1ae34ecf6..f280c6bc1 100644 --- a/Greenshot/Helpers/WindowWrapper.cs +++ b/Greenshot/Helpers/WindowWrapper.cs @@ -19,9 +19,10 @@ * along with this program. If not, see . */ using System; +using System.Windows.Forms; namespace Greenshot.Helpers { - public class WindowWrapper : System.Windows.Forms.IWin32Window { + public class WindowWrapper : IWin32Window { public WindowWrapper(IntPtr handle) { _hwnd = handle; } diff --git a/Greenshot/Memento/ChangeFieldHolderMemento.cs b/Greenshot/Memento/ChangeFieldHolderMemento.cs index c7ad2b2ec..2a062aa56 100644 --- a/Greenshot/Memento/ChangeFieldHolderMemento.cs +++ b/Greenshot/Memento/ChangeFieldHolderMemento.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ using System; -using Greenshot.Drawing; using Greenshot.Plugin.Drawing; using Greenshot.Drawing.Fields; using Greenshot.Configuration; @@ -36,7 +35,7 @@ namespace Greenshot.Memento { public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, Field fieldToBeChanged) { this.drawableContainer = drawableContainer; this.fieldToBeChanged = fieldToBeChanged; - this.oldValue = fieldToBeChanged.Value; + oldValue = fieldToBeChanged.Value; } public void Dispose() { diff --git a/Greenshot/Memento/SurfaceBackgroundChangeMemento.cs b/Greenshot/Memento/SurfaceBackgroundChangeMemento.cs index 0da0f9ff8..46c279b5b 100644 --- a/Greenshot/Memento/SurfaceBackgroundChangeMemento.cs +++ b/Greenshot/Memento/SurfaceBackgroundChangeMemento.cs @@ -35,7 +35,7 @@ namespace Greenshot.Memento { public SurfaceBackgroundChangeMemento(Surface surface, Point offset) { this.surface = surface; - this.image = surface.Image; + image = surface.Image; this.offset = new Point(-offset.X, -offset.Y); } diff --git a/Greenshot/Memento/TextChangeMemento.cs b/Greenshot/Memento/TextChangeMemento.cs index 56eca8fe3..8fb5d51e1 100644 --- a/Greenshot/Memento/TextChangeMemento.cs +++ b/Greenshot/Memento/TextChangeMemento.cs @@ -32,7 +32,7 @@ namespace Greenshot.Memento { public TextChangeMemento(TextContainer textContainer) { this.textContainer = textContainer; - this.oldText = textContainer.Text; + oldText = textContainer.Text; } public void Dispose() { diff --git a/Greenshot/Processors/TitleFixProcessor.cs b/Greenshot/Processors/TitleFixProcessor.cs index 6829a2bc6..8b41053fa 100644 --- a/Greenshot/Processors/TitleFixProcessor.cs +++ b/Greenshot/Processors/TitleFixProcessor.cs @@ -18,20 +18,21 @@ * 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.Text.RegularExpressions; using Greenshot.Plugin; using GreenshotPlugin.Core; using Greenshot.IniFile; +using log4net; namespace Greenshot.Processors { /// /// Description of TitleFixProcessor. /// public class TitleFixProcessor : AbstractProcessor { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(TitleFixProcessor)); + private static ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor)); private static CoreConfiguration config = IniConfig.GetIniSection(); public TitleFixProcessor() { diff --git a/GreenshotBoxPlugin/BoxDestination.cs b/GreenshotBoxPlugin/BoxDestination.cs index e0806dac2..3f1fedcd8 100644 --- a/GreenshotBoxPlugin/BoxDestination.cs +++ b/GreenshotBoxPlugin/BoxDestination.cs @@ -20,18 +20,17 @@ */ using System.ComponentModel; using System.Drawing; -using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; +using log4net; namespace GreenshotBoxPlugin { public class BoxDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(BoxDestination)); - private static BoxConfiguration config = IniConfig.GetIniSection(); + private static ILog LOG = LogManager.GetLogger(typeof(BoxDestination)); - private BoxPlugin plugin = null; + private readonly BoxPlugin _plugin; public BoxDestination(BoxPlugin plugin) { - this.plugin = plugin; + _plugin = plugin; } public override string Designation { @@ -54,8 +53,8 @@ namespace GreenshotBoxPlugin { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); - string uploadUrl = plugin.Upload(captureDetails, surface); + ExportInformation exportInformation = new ExportInformation(Designation, Description); + string uploadUrl = _plugin.Upload(captureDetails, surface); if (uploadUrl != null) { exportInformation.ExportMade = true; exportInformation.Uri = uploadUrl; diff --git a/GreenshotBoxPlugin/BoxPlugin.cs b/GreenshotBoxPlugin/BoxPlugin.cs index be028bd71..5443c4c40 100644 --- a/GreenshotBoxPlugin/BoxPlugin.cs +++ b/GreenshotBoxPlugin/BoxPlugin.cs @@ -35,11 +35,11 @@ namespace GreenshotBoxPlugin { /// public class BoxPlugin : IGreenshotPlugin { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(BoxPlugin)); - private static BoxConfiguration config; + private static BoxConfiguration _config; public static PluginAttribute Attributes; - private IGreenshotHost host; - private ComponentResourceManager resources; - private ToolStripMenuItem itemPlugInConfig; + private IGreenshotHost _host; + private ComponentResourceManager _resources; + private ToolStripMenuItem _itemPlugInConfig; public void Dispose() { Dispose(true); @@ -48,16 +48,13 @@ namespace GreenshotBoxPlugin { protected virtual void Dispose(bool disposing) { if (disposing) { - if (itemPlugInConfig != null) { - itemPlugInConfig.Dispose(); - itemPlugInConfig = null; + if (_itemPlugInConfig != null) { + _itemPlugInConfig.Dispose(); + _itemPlugInConfig = null; } } } - public BoxPlugin() { - } - public IEnumerable Destinations() { yield return new BoxDestination(this); } @@ -70,29 +67,30 @@ namespace GreenshotBoxPlugin { /// /// Implementation of the IGreenshotPlugin.Initialize /// - /// Use the IGreenshotPluginHost interface to register events + /// Use the IGreenshotPluginHost interface to register events /// My own attributes - public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) { - this.host = (IGreenshotHost)pluginHost; - Attributes = myAttributes; + public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute pluginAttribute) { + _host = pluginHost; + Attributes = pluginAttribute; // Register configuration (don't need the configuration itself) - config = IniConfig.GetIniSection(); - resources = new ComponentResourceManager(typeof(BoxPlugin)); + _config = IniConfig.GetIniSection(); + _resources = new ComponentResourceManager(typeof(BoxPlugin)); - itemPlugInConfig = new ToolStripMenuItem(); - itemPlugInConfig.Image = (Image)resources.GetObject("Box"); - itemPlugInConfig.Text = Language.GetString("box", LangKey.Configure); - itemPlugInConfig.Click += new System.EventHandler(ConfigMenuClick); + _itemPlugInConfig = new ToolStripMenuItem { + Image = (Image) _resources.GetObject("Box"), + Text = Language.GetString("box", LangKey.Configure) + }; + _itemPlugInConfig.Click += ConfigMenuClick; - PluginUtils.AddToContextMenu(host, itemPlugInConfig); - Language.LanguageChanged += new LanguageChangedHandler(OnLanguageChanged); + PluginUtils.AddToContextMenu(_host, _itemPlugInConfig); + Language.LanguageChanged += OnLanguageChanged; return true; } public void OnLanguageChanged(object sender, EventArgs e) { - if (itemPlugInConfig != null) { - itemPlugInConfig.Text = Language.GetString("box", LangKey.Configure); + if (_itemPlugInConfig != null) { + _itemPlugInConfig.Text = Language.GetString("box", LangKey.Configure); } } @@ -104,7 +102,7 @@ namespace GreenshotBoxPlugin { /// Implementation of the IPlugin.Configure /// public virtual void Configure() { - config.ShowConfigDialog(); + _config.ShowConfigDialog(); } /// @@ -118,26 +116,26 @@ namespace GreenshotBoxPlugin { } public void ConfigMenuClick(object sender, EventArgs eventArgs) { - config.ShowConfigDialog(); + _config.ShowConfigDialog(); } /// /// This will be called when the menu item in the Editor is clicked /// public string Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload) { - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(config.UploadFormat, config.UploadJpegQuality, false); + SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false); try { string url = null; - string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); + string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails)); SurfaceContainer imageToUpload = new SurfaceContainer(surfaceToUpload, outputSettings, filename); - new PleaseWaitForm().ShowAndWait(BoxPlugin.Attributes.Name, Language.GetString("box", LangKey.communication_wait), - delegate() { + new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("box", LangKey.communication_wait), + delegate { url = BoxUtils.UploadToBox(imageToUpload, captureDetails.Title, filename); } ); - if (url != null && config.AfterUploadLinkToClipBoard) { + if (url != null && _config.AfterUploadLinkToClipBoard) { ClipboardHelper.SetClipboardData(url); } diff --git a/GreenshotBoxPlugin/BoxUtils.cs b/GreenshotBoxPlugin/BoxUtils.cs index 4da805c40..3610cca74 100644 --- a/GreenshotBoxPlugin/BoxUtils.cs +++ b/GreenshotBoxPlugin/BoxUtils.cs @@ -57,7 +57,7 @@ namespace GreenshotBoxPlugin { } string authorizationResponse = PostAndReturn(new Uri(TokenUri), string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}", callbackParameters["code"], BoxCredentials.ClientId, BoxCredentials.ClientSecret)); - var authorization = JSONSerializer.Deserialize(authorizationResponse); + var authorization = JsonSerializer.Deserialize(authorizationResponse); Config.BoxToken = authorization.AccessToken; IniConfig.Save(); @@ -67,15 +67,16 @@ namespace GreenshotBoxPlugin { /// /// Download a url response as string /// - /// An Uri to specify the download location + /// An Uri to specify the download location + /// /// string with the file content public static string PostAndReturn(Uri url, string postMessage) { HttpWebRequest webRequest = (HttpWebRequest)NetworkHelper.CreateWebRequest(url); webRequest.Method = "POST"; webRequest.KeepAlive = true; - webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; + webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.ContentType = "application/x-www-form-urlencoded"; - byte[] data = Encoding.UTF8.GetBytes(postMessage.ToString()); + byte[] data = Encoding.UTF8.GetBytes(postMessage); using (var requestStream = webRequest.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } @@ -172,12 +173,12 @@ namespace GreenshotBoxPlugin { IniConfig.Save(); continue; } - var upload = JSONSerializer.Deserialize(response); + var upload = JsonSerializer.Deserialize(response); if (upload == null || upload.Entries == null || upload.Entries.Count == 0) return null; if (Config.UseSharedLink) { string filesResponse = HttpPut(string.Format(FilesUri, upload.Entries[0].Id), "{\"shared_link\": {\"access\": \"open\"}}"); - var file = JSONSerializer.Deserialize(filesResponse); + var file = JsonSerializer.Deserialize(filesResponse); return file.SharedLink.Url; } return string.Format("http://www.box.com/files/0/f/0/1/f_{0}", upload.Entries[0].Id); @@ -187,7 +188,7 @@ namespace GreenshotBoxPlugin { /// /// A simple helper class for the DataContractJsonSerializer /// - public static class JSONSerializer { + internal static class JsonSerializer { /// /// Helper method to serialize object to JSON /// diff --git a/GreenshotConfluencePlugin/ConfluencePlugin.cs b/GreenshotConfluencePlugin/ConfluencePlugin.cs index a55e5662d..a45346530 100644 --- a/GreenshotConfluencePlugin/ConfluencePlugin.cs +++ b/GreenshotConfluencePlugin/ConfluencePlugin.cs @@ -18,14 +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.Collections.Generic; -using System.Web; -using System.Windows; + using Confluence; using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; +using System; +using System.Collections.Generic; +using System.Windows; using TranslationByMarkupExtension; namespace GreenshotConfluencePlugin { @@ -34,10 +34,8 @@ namespace GreenshotConfluencePlugin { /// public class ConfluencePlugin : IGreenshotPlugin { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluencePlugin)); - private static ConfluenceConnector confluenceConnector = null; - private static PluginAttribute ConfluencePluginAttributes; - private static ConfluenceConfiguration config = null; - private static IGreenshotHost host; + private static ConfluenceConnector _confluenceConnector; + private static ConfluenceConfiguration _config; public void Dispose() { Dispose(true); @@ -49,45 +47,40 @@ namespace GreenshotConfluencePlugin { } private static void CreateConfluenceConntector() { - if (confluenceConnector == null) { - if (config.Url.Contains("soap-axis")) { - confluenceConnector = new ConfluenceConnector(config.Url, config.Timeout); + if (_confluenceConnector == null) { + if (_config.Url.Contains("soap-axis")) { + _confluenceConnector = new ConfluenceConnector(_config.Url, _config.Timeout); } else { - confluenceConnector = new ConfluenceConnector(config.Url + ConfluenceConfiguration.DEFAULT_POSTFIX2, config.Timeout); + _confluenceConnector = new ConfluenceConnector(_config.Url + ConfluenceConfiguration.DEFAULT_POSTFIX2, _config.Timeout); } } } public static ConfluenceConnector ConfluenceConnectorNoLogin { get { - return confluenceConnector; + return _confluenceConnector; } } public static ConfluenceConnector ConfluenceConnector { get { - if (confluenceConnector == null) { + if (_confluenceConnector == null) { CreateConfluenceConntector(); } try { - if (!confluenceConnector.isLoggedIn) { - confluenceConnector.login(); + if (_confluenceConnector != null && !_confluenceConnector.isLoggedIn) { + _confluenceConnector.login(); } } catch (Exception e) { MessageBox.Show(Language.GetFormattedString("confluence", LangKey.login_error, e.Message)); } - return confluenceConnector; + return _confluenceConnector; } } - public ConfluencePlugin() { - } - public IEnumerable Destinations() { if (ConfluenceDestination.IsInitialized) { yield return new ConfluenceDestination(); - } else { - yield break; } } @@ -98,16 +91,12 @@ namespace GreenshotConfluencePlugin { /// /// Implementation of the IGreenshotPlugin.Initialize /// - /// Use the IGreenshotPluginHost interface to register events - /// Use the ICaptureHost interface to register in the MainContextMenu - /// My own attributes + /// Use the IGreenshotPluginHost interface to register events + /// My own attributes public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) { - host = pluginHost; - ConfluencePluginAttributes = myAttributes; - // Register configuration (don't need the configuration itself) - config = IniConfig.GetIniSection(); - if(config.IsDirty) { + _config = IniConfig.GetIniSection(); + if(_config.IsDirty) { IniConfig.Save(); } try { @@ -122,9 +111,9 @@ namespace GreenshotConfluencePlugin { public virtual void Shutdown() { LOG.Debug("Confluence Plugin shutdown."); - if (confluenceConnector != null) { - confluenceConnector.logout(); - confluenceConnector = null; + if (_confluenceConnector != null) { + _confluenceConnector.logout(); + _confluenceConnector = null; } } @@ -132,20 +121,20 @@ namespace GreenshotConfluencePlugin { /// Implementation of the IPlugin.Configure /// public virtual void Configure() { - ConfluenceConfiguration clonedConfig = config.Clone(); + ConfluenceConfiguration clonedConfig = _config.Clone(); ConfluenceConfigurationForm configForm = new ConfluenceConfigurationForm(clonedConfig); - string url = config.Url; + string url = _config.Url; Nullable dialogResult = configForm.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value) { // copy the new object to the old... - clonedConfig.CloneTo(config); + clonedConfig.CloneTo(_config); IniConfig.Save(); - if (confluenceConnector != null) { - if (!url.Equals(config.Url)) { - if (confluenceConnector.isLoggedIn) { - confluenceConnector.logout(); + if (_confluenceConnector != null) { + if (!url.Equals(_config.Url)) { + if (_confluenceConnector.isLoggedIn) { + _confluenceConnector.logout(); } - confluenceConnector = null; + _confluenceConnector = null; } } } diff --git a/GreenshotPlugin/Core/Objects.cs b/GreenshotPlugin/Core/Objects.cs index 612520264..c34ac9814 100644 --- a/GreenshotPlugin/Core/Objects.cs +++ b/GreenshotPlugin/Core/Objects.cs @@ -40,7 +40,7 @@ namespace GreenshotPlugin.Core { } // Don't serialize a null object, simply return the default for that object - if (Object.ReferenceEquals(source, null)) { + if (ReferenceEquals(source, null)) { return default(T); }