Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘bool’

C# code snippet to get a screenshot of a process

A small code snippet to get a screenshot of a process

Screenshot of this application.

image

Code behinds

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ProcessScreenshot
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnTake_Click(object sender, EventArgs e)
        {
            Process[] ps = Process.GetProcessesByName(txtProcess.Text.Trim());
            if (ps.Length == 0)
            {
                MessageBox.Show(string.Format("There is no process named {0}", txtProcess.Text));
                return;
            }
            Process proc = Process.GetProcessesByName("notepad")[0];
            if (SetForegroundWindow(proc.MainWindowHandle))
            {
                RECT srcRect;
                if (!proc.MainWindowHandle.Equals(IntPtr.Zero))
                {
                    if (GetWindowRect(proc.MainWindowHandle, out srcRect))
                    {
                        int width = srcRect.Right - srcRect.Left;
                        int height = srcRect.Bottom - srcRect.Top;

                        var bmp = new Bitmap(width, height);
                        Graphics screenG = Graphics.FromImage(bmp);

                        try
                        {
                            screenG.CopyFromScreen(srcRect.Left, srcRect.Top,
                                                   0, 0, new Size(width, height),
                                                   CopyPixelOperation.SourceCopy);

                            if (!Directory.Exists(txtPath.Text))
                                Directory.CreateDirectory(txtPath.Text);

                            string fileName = DateTime.Now.ToString("HHmmss-") +
                                              Guid.NewGuid().ToString().Substring(0, 6) + ".png";
                            bmp.Save(Path.Combine(txtPath.Text.Trim(), fileName), ImageFormat.Png);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        finally
                        {
                            screenG.Dispose();
                            bmp.Dispose();
                        }
                    }
                }
            }
        }

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        #region Nested type: RECT

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        #endregion
    }
}

Optional Parameters in C# 4.0

The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. Default values must be constants.

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list are not supported. For example, in the following code, instance method ExampleMethod is defined with one required and two optional parameters.

E.g.

public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)

The following call to ExampleMethod causes a compiler error, because an  argument is provided for the third parameter but not for the second.

//anExample.ExampleMethod(3,  ,4);

However, if you  know the name of the third parameter, you can use a named argument to  accomplish the task.

anExample.ExampleMethod(3, optionalint: 4);

IntelliSense uses brackets to  indicate optional parameters, as shown in the following illustration.
Optional parameters in ExampleMethod
Consider a standard scenario with method overloading or constructor chaining.  In C# we’d have several methods with different signatures where, in effect, we’re really just after default values. Let’s take the scenario where we’ve got a little helper class to send emails in our application. In some cases we want to CC the administrator to troubleshoot issues; in some cases we want rich HTML emails rather than plain text. We might set up our methods like this: 1:  public void SendMail(string toAddress, string bodyText) 2:  { 3:      this.SendMail(toAddress, bodyText, true); 4:  } 5:    6:  public void SendMail(string toAddress, string bodyText, bool ccAdministrator) 7:  { 8:      this.SendMail(toAddress, bodyText, ccAdministrator, false); 9:  } 10:    11:  public void SendMail(string toAddress, string bodyText, bool ccAdministrator, bool isBodyHtml) 12:  { 13:      // Full implementation here 14:  } This is pretty standard method overloading and we essentially are setting default values (true for CC the Admin, and false for HTML emails). With C# 4.0 we can now make the code more concise by only having to implement 1 method: 1:  public void SendMail(string toAddress, string bodyText, bool ccAdministrator = true, bool isBodyHtml = false) 2:  { 3:      // Full implementation here 4:  } However, you do have to take into account your scenario.  If you have a situation where you actually need to know if the consuming code provided a value then this isn’t a good option because if “true” comes in for the 3rd parameter, you don’t know if the consuming code actually set this explicitly or if it was simply the result of the default value.  But in typical scenarios like this, it’s not a big deal.  Cracking open Reflector and looking at the IL that the C# compiler is generating: 1:  .method public hidebysig instance void SendMail(string toAddress, string bodyText, [opt] bool ccAdministrator, [opt] bool isBodyHtml) cil managed 2:  { 3:      .param [3] = bool(true) 4:      .param [4] = bool(false) 5:      .maxstack 8 6:      L_0000: nop 7:      L_0001: ret 8:  } Which Reflectors translates to a C# equivalent of: 1:  public void SendMail(string toAddress, string bodyText, [Optional, DefaultParameterValue(true)] bool ccAdministrator, [Optional, DefaultParameterValue(false)] bool isBodyHtml) 2:  { 3:  }