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 ‘system diagnostics’

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
    }
}

How to launch a process with admin rights from a Visual Studio 2008 add-in on Windows System with UAC.

While on Windows XP by default every user is an administrator (although you can create “standard” users) Windows Vista introduces a new feature named User Account Control (UAC) which causes that by default even administrators run as standard users. When a process requires administrator rights to run, the operating system prompts for an “elevation prompt”.

Here is a demo:

System.Diagnostics.Process process = null;
System.Diagnostics.ProcessStartInfo processStartInfo;

processStartInfo = new System.Diagnostics.ProcessStartInfo();

processStartInfo.FileName = "regedit.exe";

if (System.Environment.OSVersion.Version.Major >= 6)  // Windows Vista or higher
{
   processStartInfo.Verb = "runas";
}
else
{
   // No need to prompt to run as admin
}

processStartInfo.Arguments = "";
processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;

try
{
   process = System.Diagnostics.Process.Start(processStartInfo);
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
   if (process != null)
   {
      process.Dispose();
   }
}