Archive for July, 2014
Capture an Image of the Desktop, Specific Screen or Portion of a Screen with C#
Posted by Kelly's Chronicles in .NET, C# on July 21, 2014
So today is my birthday. It has been a wild ride this last 46 years. Lets hope that things continue to get better.
So this is my entire class for capturing screens and desktop appearance to an image file or to print them. I use this class quite often in my error management, saving or emailing the output should errors occur so I can get a good idea of what was going on at the time an error occurs. Why? Because often end users or business analysts, though they are trying their best, sometimes can’t describe in detail how to reproduce what occurred. I suggest using this in conjunction with a logging class as well so that you can replicate the steps needed. The image file is also very handy in reconstructing what a user was or was not doing which, as a coder, can literally save your ass on occasion. So here it is. It is well commented and pretty straight forward.
using System.Windows.Forms;
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
public class clsScreenCapture
{
private System.Drawing.Printing.PrintDocument Pd = new System.Drawing.Printing.PrintDocument();
private PictureBox PicForm = new PictureBox();
/// Creates an Image object containing a screen shot of the entire desktop
public Image CaptureScreen()
{
return CaptureWindow(User32.GetDesktopWindow());
} //CaptureScreen
/// Creates an Image object containing a screen shot of a specific window
public Image CaptureWindow(IntPtr handle)
{
int SRCCOPY = 0xCC0020;
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle, ref windowRect);
int width = windowRect.right – windowRect.left;
int height = windowRect.bottom – windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
// using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, SRCCOPY);
// restore selection
GDI32.SelectObject(hdcDest, hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle, hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
} //CaptureWindow
/// Captures a screen shot of a specific window, and saves it to a file
public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
{
Image img = CaptureWindow(handle);
img.Save(filename, format);
} //CaptureWindowToFile
/// Captures a screen shot of a specific window, and saves it to a file
public void CaptureWindowToPrinter(Form mfForm, ImageFormat format)
{
// Dim img As Image = CaptureScreen()
Image img = CaptureWindow(mfForm.Handle);
try
{
PicForm.Image = img;
if (MessageBox.Show(“Press Yes to Print or No to Copy to your Clipboard (‘No’ will allow pasting into an email or Word document etc).”, “Print or Copy to Clipboard?”, MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Pd.Print();
}
else
{
Clipboard.SetDataObject(img, true);
}
}
catch (Exception ex)
{
string a = “vfdgsfg”;
}
} //CaptureWindowToPrinter
private void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//—————————————————————
// this procedure handles events raised by the printer object pd
//—————————————————————
e.Graphics.DrawImageUnscaled(PicForm.Image, 0, 0); //send image to printer – upper left position
e.HasMorePages = false; //this is the last page to print
}
/// Captures a screen shot of the entire desktop, and saves it to a file
public void CaptureScreenToFile(string filename, ImageFormat format)
{
Image img = CaptureScreen();
img.Save(filename, format);
} //CaptureScreenToFile
public Bitmap CaptureDeskTopRectangle(Rectangle CapRect, int CapRectWidth, int CapRectHeight)
{
/// Returns BitMap of the region of the desktop, similar to CaptureWindow, but can be used to
/// create a snapshot of the desktop when no handle is present, by passing in a rectangle
/// Grabs snapshot of entire desktop, then crops it using the passed in rectangle’s coordinates
clsScreenCapture SC = new clsScreenCapture();
Bitmap bmpImage = new Bitmap(SC.CaptureScreen());
Bitmap bmpCrop = new Bitmap(CapRectWidth, CapRectHeight, bmpImage.PixelFormat);
Rectangle recCrop = new Rectangle(CapRect.X, CapRect.Y, CapRectWidth, CapRectHeight);
Graphics gphCrop = Graphics.FromImage(bmpCrop);
Rectangle recDest = new Rectangle(0, 0, CapRectWidth, CapRectHeight);
gphCrop.DrawImage(bmpImage, recDest, recCrop.X, recCrop.Y, recCrop.Width, recCrop.Height, GraphicsUnit.Pixel);
return bmpCrop;
}
/// Helper class containing Gdi32 API functions
private class GDI32
{
public int SRCCOPY = 0xCC0020;
// BitBlt dwRop parameter
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”BitBlt”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 BitBlt(IntPtr hDestDC, Int32 x, Int32 y, Int32 nWidth, Int32 nHeight, IntPtr hSrcDC, Int32 xSrc, Int32 ySrc, Int32 dwRop);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”CreateCompatibleBitmap”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, Int32 nWidth, Int32 nHeight);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”CreateCompatibleDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”DeleteDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 DeleteDC(IntPtr hdc);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”DeleteObject”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 DeleteObject(IntPtr hObject);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”SelectObject”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
} //GDI32
/// Helper class containing User32 API functions
public class User32
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
} //RECT
[System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetDesktopWindow”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr GetDesktopWindow();
[System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetWindowDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr GetWindowDC(IntPtr hwnd);
[System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”ReleaseDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
[System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetWindowRect”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 GetWindowRect(IntPtr hwnd, ref RECT lpRect);
} //User32
public clsScreenCapture()
{
SubscribeToEvents();
}
// event handler wireups:
private bool EventsSubscribed = false;
private void SubscribeToEvents()
{
if (EventsSubscribed)
return;
else
EventsSubscribed = true;
Pd.PrintPage += pd_PrintPage;
}
}
.NET, analysts, Ansi, appearance, BitBlt, Bitmap, bmpCrop, bmpImage, c#, CapRect, CapRectWidth, Capture, CaptureDeskTopRectangle, Captures, CaptureScreenToFile, CaptureWindowToFile, CaptureWindowToPrinter, CharSet, Clipboard, clsScreenCapture, conjunction, Context, Copy, CreateCompatibleBitmap, CreateCompatibleDC, Creates, DeleteDC, DeleteObject, Desktop, device, DialogResult, DllImport, DrawImage, dwRop, EntryPoint, error, errors, event, events, Exception, extern, filename, Form, Forms, FromHbitmap, FromImage, GetDeviceCaps, GetWindowDC, GetWindowRect, gphCrop, Grabs, graphics, GraphicsUnit, Handle, handler, HasMorePages, hBitmap, hdcDest, hdcSrc, Helper, hObject, hwnd, Image, ImageFormat, InteropServices, IntPtr, Lets, management, MessageBox, MessageBoxButtons, mfForm, nWidth, output, parameter, pd_PrintPage, PicForm, PictureBox, Pixel, PixelFormat, Portion, Print, PrintDocument, printer, PrintPage, PrintPageEventArgs, procedure, recCrop, recDest, RECT, Rectangle, region, ReleaseDC, Returns, Runtime, Save, Selection, SelectObject, sender, Sequential, SetDataObject, SetLastError, size, snapshot, Specific, SRCCOPY, StructLayout, SubscribeToEvents, System, user, users, Width, windowRect, Windows, Word, YesNo
Encryption and Decryption of strings with C#
Posted by Kelly's Chronicles in .NET, C#, vb.net on July 11, 2014
Well I am checking out the Beale Street Historic District for the first time in Memphis, TN tonight. I have heard a lot about it since my arrival here so am excited to get to go. I think it will be fun.
Of course this would come up. I had written this previously in vb.net and I had the opportunity to use it again today. Of course in doing so, I discovered a bad coding practice violation I had committed. I had failed to return a value in my function’s Catch block of my code. C# doesn’t let you off the hook so easily and will bug you till you fix it. As noted previously, topic is encryption and decryption of strings. It is straightforward but you might find it useful. Simply pass in the string you want to encrypt/decrypt and the key you want to use.
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class Crypto
{
private static TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
private static MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
public static byte[] MD5Hash(string value)
{
return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value));
}
public static string Encrypt(string stringToEncrypt, string key)
{
DES.Key = Crypto.MD5Hash(key);
DES.Mode = CipherMode.ECB;
byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt);
return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length));
}
public static string Decrypt(string encryptedString, string key)
{
try
{
DES.Key = Crypto.MD5Hash(key);
DES.Mode = CipherMode.ECB;
byte[] Buffer = Convert.FromBase64String(encryptedString);
return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length));
}
catch (Exception ex)
{
MessageBox.Show(“Invalid Key”, “Decryption Failed”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
// Inserted the following ‘return’ since all code paths must return a value in C#:
return null;
}
}
And now it’s usage…..
public class Form1
{
private void Button1_Click(object sender, System.EventArgs e)
{
string key = Microsoft.VisualBasic.Interaction.InputBox(“Enter a Key:”, “”, “”, -1, -1);
Label1.Text = Crypto.Encrypt(TextBox1.Text, key);
TextBox1.Clear();
}
private void Button2_Click(object sender, System.EventArgs e)
{
string key = Microsoft.VisualBasic.Interaction.InputBox(“Enter a Key:”, “”, “”, -1, -1);
TextBox1.Text = Crypto.Decrypt(Label1.Text, key);
}
}
arrival, ASCII, Beale, Buffer, byte, Catch, CipherMode, Clear, ComputeHash, Convert, CreateDecryptor, CreateEncryptor, Crypto, Cryptography, Decrypt, Decryption, District, Encrypt, Encryption, Enter, EventArgs, Exception, Exclamation, Facebook, GetBytes, Historic, InputBox, Interaction, Invalid, Join, Length, Memphis, MessageBox, MessageBoxButtons, MessageBoxIcon, Microsoft, Mode, paths, sender, situation, Street, stringToEncrypt, System, Text, topic, TransformFinalBlock, TripleDESCryptoServiceProvider, usage, violation, VisualBasic
Create Computer Account in Active Directory and add it to Domain with C#
Posted by Kelly's Chronicles in .NET, C#, Computers and Internet on July 10, 2014
I was asked to convert this code from my original post to C# by a friend who obviously didn’t want to do it himself. There was one conversion issue along the way I also fixed which is why I suspect he didn’t convert it himself. In other news, my assimilation into Memphis, TN is going well. I am slowly becoming accustomed to the heat and humidity and am trying to fight off the urge to eat everything in sight because the food is just amazing if a tad bit unhealthy. I finally am getting my car fixed and am looking forward to getting out and seeing this town for myself. Let’s hope it will be a lot of fun. Ok back to what you came here for. Here you go…..
DirectoryEntry Entry = new DirectoryEntry(“LDAP://” + ActiveDirectoryTree.SelectedNode.Name, strDomain + “\\” + strUser, strPass, AuthenticationTypes.Secure);
string ComputerName = null;
string CompSystem = null;
int ComputerCount = ComputerList.Items.Count;
int i = 0;
for (i = 0; i <= ComputerCount – 1; i++)
{
CompSystem = ComputerList.Items(i).Text;
DirectoryEntry ComputerEntry = Entry.Children.Add(“CN=” + CompSystem + “”, “Computer”);
ComputerEntry.Properties(“sAMAccountName”).Value = “” + CompSystem + “”;
ComputerEntry.CommitChanges();
int exp = Convert.ToInt32(ComputerEntry.Properties(“UserAccountControl”).Value);
ComputerEntry.Properties(“UserAccountControl”).Value = exp | 0x1;
ComputerEntry.CommitChanges();
int val = Convert.ToInt32(ComputerEntry.Properties(“UserAccountControl”).Value);
ComputerEntry.Properties(“UserAccountControl”).Value = val & ~0x2;
ComputerEntry.CommitChanges();
ComputersCreated.Text = ComputersCreated.Text + CompSystem + Environment.NewLine;
ComputerEntry.Close();
ComputerEntry.Dispose();
}
ComputersCreated.Text = ComputersCreated.Text + “——————————” + Environment.NewLine;
Entry.Close();
Entry.Dispose();
and to add to the domain:
string[] args = new string[5];
string[] args2 = new string[3];
// The one difference from the vb.net version. Commented this declaration since looping variables in ‘foreach’
//loops are declared in the ‘foreach’ header in C#:
// ManagementObject comp = null;
ManagementObjectCollection comps = null;
ManagementClass clsComps = new ManagementClass(“Win32_ComputerSystem”);
comps = clsComps.GetInstances();
foreach (ManagementObject comp in comps)
{
// this == used to join the domain
args[0] = “DOMAIN to join”;
args[1] = “Password”;
args[2] = “User with domain privs”;
args[3] = “Specify OU Here (ou=test,dc=domain,dc=com)”;
args[4] = “1”;
UInt32 retVal = 0;
retVal = comp.InvokeMethod(“JoinDomainOrWorkgroup”, args);
retval2 = Convert.ToString(retVal);
if (retval2 == “0”)
{
MessageBox.Show(“Welcome to the domain”);
Close();
}
else
{
End If
}
.NET, Account, Active, ActiveDirectoryTree, assimilation, AuthenticationTypes, c#, Children, Close, clsComps, CommitChanges, CompSystem, computer, ComputerCount, ComputerEntry, ComputerList, ComputerName, Convert, Count, Create, declaration, difference, Directory, DirectoryEntry, Dispose, Domain, Entry, environment, Facebook, food, foreach, friend, GetInstances, header, Here, InvokeMethod, items, Join, JoinDomainOrWorkgroup, LDAP, ManagementClass, ManagementObject, ManagementObjectCollection, Memphis, MessageBox, Name, NewLine, news, Password, properties, retVal, Secure, SelectedNode, Specify, Text, user, UserAccountControl, Value, vb.net, version, Welcome
-
You are currently browsing the archives for July, 2014
Recent Comments
Archives
- April 2018
- January 2018
- December 2017
- June 2017
- May 2017
- May 2016
- April 2016
- September 2015
- July 2014
- June 2014
- November 2012
- October 2012
- June 2012
- May 2012
- April 2012
- January 2012
- September 2011
- August 2011
- July 2011
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- August 2008
- July 2008
- June 2008
- May 2008
Get or Write Image Metadata with C#
Posted by Kelly's Chronicles in .NET, C#, vb.net on July 15, 2014
Good morning! it’s always fun when old code gets to get used again. And it gave me an opportunity to convert this snippet to C#. Basically what we are trying to do is write or get metadata to an image. As those folks who commented on the previous post noted, this code will not remove existing metadata. It is a problem I still have not found a solution for however. If any of you know the answer please let us know! Anyway here it is converted and still useable after all this time.
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.IO;
public class clsReadMetaData
{
public ImageMetadata ReadEXIFMetadata(string filepath)
{
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
Image image__1 = Image.FromStream(fs);
PropertyItem[] imagePropertyItems = image__1.PropertyItems;
ImageMetadata imageMetadata = new ImageMetadata();
foreach (PropertyItem pi in imagePropertyItems)
{
switch ((EXIFProperty)pi.Id)
{
case EXIFProperty.Title:
imageMetadata.Title = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Title = Encoding.UTF32.GetString(pi.Value)
break;
case EXIFProperty.Author:
imageMetadata.Author = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Author = Encoding.UTF8.GetString(pi.Value)
break;
case EXIFProperty.Keywords:
imageMetadata.Keywords = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Keywords = Encoding.UTF8.GetString(pi.Value)
break;
case EXIFProperty.Comments:
imageMetadata.Comments = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Comments = Encoding.UTF8.GetString(pi.Value)
break;
default:
break;
}
}
fs.Close();
return imageMetadata;
}
public void SaveEXIFMetadata(Image image, ImageMetadata metadata, string filepath)
{
SaveEXIFMetadataProperty(image, EXIFProperty.Title, metadata.Title, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Author, metadata.Author, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Keywords, metadata.Keywords, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Comments, metadata.Comments, filepath);
}
private void SaveEXIFMetadataProperty(Image image, EXIFProperty property, string propertyValue, string filepath)
{
PropertyItem propertyItem = CreatePropertyItem();
propertyItem.Id = Convert.ToInt32(property);
// Type=1 means Array of Bytes.
propertyItem.Type = 2;
propertyItem.Len = propertyValue.Length;
//propertyItem.Value = Encoding.Unicode.GetBytes(propertyValue)
propertyItem.Value = Encoding.UTF8.GetBytes(propertyValue);
image.SetPropertyItem(propertyItem);
image.Save(filepath);
}
private PropertyItem CreatePropertyItem()
{
System.Reflection.ConstructorInfo ci = typeof(PropertyItem).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null);
return (PropertyItem)ci.Invoke(null);
}
}
public enum EXIFProperty
{
Title = 40091,
Author = 40093,
Keywords = 40094,
Comments = 40092
}
public class ImageMetadata
{
private string _title = string.Empty;
private string _author = string.Empty;
private string _keywords = string.Empty;
private string _comments = string.Empty;
public ImageMetadata()
{
this._title = string.Empty;
this._author = string.Empty;
this._keywords = string.Empty;
this._comments = string.Empty;
}
public ImageMetadata(string title, string author, string keywords, string comments)
{
this._title = title;
this._author = author;
this._keywords = keywords;
this._comments = comments;
}
public string Title
{
get
{
return this._title;
}
set
{
this._title = value;
}
}
public string Author
{
get
{
return this._author;
}
set
{
this._author = value;
}
}
public string Keywords
{
get
{
return this._keywords;
}
set
{
this._keywords = value;
}
}
public string Comments
{
get
{
return this._comments;
}
set
{
this._comments = value;
}
}
}
Join me on Facebook
Anyway, Array, author, BindingFlags, Bytes, Close, Collections, Comments, ConstructorInfo, Convert, CreatePropertyItem, FileMode, filepath, FileStream, FromStream, Generic, GetBytes, GetConstructor, Image, ImageMetadata, imagePropertyItems, instance, Keywords, Length, Metadata, NonPublic, Open, PropertyItem, PropertyItems, propertyValue, Public, Read, ReadEXIFMetadata, Reflection, Save, SaveEXIFMetadata, SetPropertyItem, snippet, solution, System, Text, Title, Type, Unicode, Value, Write, _author, _comments, _keywords, _title
Leave a comment