c sharp QR CODE IMAGE

using  Csharp you can Generate  a QR Code image for your url or  text  you may use it  to store your contact information  in QR images.




















the following QR image is generated using above app  if you have a QR image Reader you   Scan the following image


Source Code :     Download Reference File  Messingtoolkit.qrcode.dll

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
using ThoughtWorks.QRCode.Codec.Util;
using System.Drawing.Imaging;
using System.IO;
namespace QR_Code_Final
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       

        private void encode_Click(object sender, EventArgs e)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            Image image;
            String data = textBox1.Text;
            image = qrCodeEncoder.Encode(data);
            pictureBox1.Image = image;
        }

        private void Save_Click(object sender, EventArgs e)
        {
           SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "JPEG (*.JPEG)|*.JPEG|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.Image.Save(saveFileDialog1.FileName, ImageFormat.Jpeg);
            
            }
          
        }



        public DialogResult Syst { get; set; }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

     
        }
    }


c sharp Controlling system volume

In this tutorial I will be showing you how you would go about controlling your system volume in C#. The reason for this tutorial is simple, Ive been asked too many times how to do it, so I thought it appropriate to write a tutorial showing how to do this task. Before we get into any code, you need to understand that this tutorial in an advanced tutorial, using Win32 API calls, custom structures, and the like. If you are not familiar with those items, I suggest you study them before attempting this tutorial.

Controlling your system volume takes a lot of advanced coding, because you have to hook into the operating system in order to gain access to the controls needed, thats the reason for all the Win32 API's. The easiest way to do this is by using a mixer control, which is what we will be doing in this tutorial. This tutorial may be rather long, as this is a complete class library, with class files for:


  • All the Win32 API Calls
  • All the structures
  • All the constants needed
  • Class for doing the actual work


I will start by showing the other 3 classes first, so you can see first hand the items needed for taking control of the system's volume controls.

The first class we will see is the Win32 API class. In this class is where we will be storing all the Win32 calls needed for controlling the sound. Since each section is it's own class, we will need to reference certain Namespaces for each class. The Namespaces we need for the Win32 class are:


1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Runtime.InteropServices;
5//custom Namespaces
6using VolumeControl.Library.Constants;
7using VolumeControl.Library.Structs;



You will notice there are 2 custom Namespaces, those are our other class files we will be getting to shortly. Since our classes reference custom Namespaces, you should have guessed that all the class are a member of the VolumeControl.Library Namespace, but each also have an appendage to that, depending on which class it is. The Namespaces we create are:

  • VolumeControl.Library.Structs
  • VolumeControl.Library.Win32
  • VolumeControl.Library.Constants


The Namespace for the Win32 class is, you guessed it, VolumeControl.Library.Win32, I am going to make an assumption here, since you continued to read along in this tutorial I'm assuming you know about Win32 API calls, and how to look up their function if you needed to, so I am not going to go into great detail about what these API calls do. If you want to look them up, a good place to start is PInvoke.Net, they have pretty much every Win32 API in programming.

In this class we have Win32 API's for opening a mixer control, closing a mixer control, getting the details of the current mixer control, getting the ID of the mixer control, and more. Here are the Win32 API's we will be needing:

  • mixerClose
  • mixerGetControlDetailsA
  • mixerGetDevCapsA
  • mixerGetID
  • mixerGetLineControlsA
  • mixerGetLineInfoA
  • mixerGetNumDevs
  • mixerMessage
  • mixerOpen
  • mixerSetControlDetails







NOTE: You will notice that the first 3 class are all declared as static, this is done so we don't have to create an instance of the class to use the items it contains. As with structs, there is a raging debate over using static classes, as far as I'm concerned the jury is still out on this.

Now on to the class that actually does all the work. In this class we have 4 methods, 1 for getting the mixer control, 1 for setting the mixer control, 1 for getting the current volume level, and finally 1 for setting the volume level. First the method for getting the mixer control. In this method we will be creating a new mixer control, we will retrieve it and use the method for setting its properties to set all the information we need for the mixer.

In this class you will be using many methods of the Marshal Class, located in the System.Runtime.InteropServices Namespace. We will be allocating memory blocks for our mixer control using the AllocCoTaskMem Method, we will be grabbing the size of our unmanaged type using the Marshal.SizeOf Method and more.

This is one of the reasons I said at the start of this tutorial that it is an advanced tutorial, and requires a firm grasp of the language, and the objects used, to understand what is going on. Before we can write any code that is going to work, we need to make sure we have references to the proper Namespaces, here are the Namespaces you will need to reference:


using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

using System.Windows.Forms;

custom Namespaces

using VolumeControl.Library.Constants;

using VolumeControl.Library.Structs;

using VolumeControl.Library.Win32;


Now for the first method in our class, the GetMixer method:


01/// <summary>
02/// method to retrieve a mixer control
03/// </summary>
04/// <param name="i"></param>
05/// <param name="type"></param>
06/// <param name="ctrlType"></param>
07/// <param name="mixerControl"></param>
08/// <param name="currVolume"></param>
09/// <returns></returns>
10private static bool GetMixer(int i, int type, int ctrlType, out VolumeStructs.Mixer mixerControl, out int currVolume)
11{
12    //create our method level variables
13    int details;
14    bool bReturn;
15    currVolume = -1;
16
17    //create our struct objects
18    VolumeStructs.LineControls lineControls = new VolumeStructs.LineControls();
19    VolumeStructs.MixerLine line = new VolumeStructs.MixerLine();
20    VolumeStructs.MixerDetails mcDetails = new VolumeStructs.MixerDetails();
21    VolumeStructs.UnsignedMixerDetails detailsUnsigned = new VolumeStructs.UnsignedMixerDetails();
22
23    //create a new mixer control
24    mixerControl = new VolumeStructs.Mixer();
25    
26    //set the properties of out mixerline object
27    line.cbStruct = Marshal.SizeOf(line);
28    line.dwComponentType = type;
29    //get the line info and assign it to our details variable
30    details = PCWin32.mixerGetLineInfoA(i, ref line, VolumeConstants.MIXER_GETLINEINFOF_COMPONENTTYPE);
31
32    //make sure we didnt receive any errors
33    if (VolumeConstants.MMSYSERR_NOERROR == details)
34    {
35        int mcSize = 152;
36        //get the size of the unmanaged type
37        int control = Marshal.SizeOf(typeof(VolumeStructs.Mixer));
38        //allocate a block of memory
39        lineControls.pamxctrl = Marshal.AllocCoTaskMem(mcSize);
40        //get the size of the line controls
41        lineControls.cbStruct = Marshal.SizeOf(lineControls);
42
43        //set properties for our mixer control
44        lineControls.dwLineID = line.dwLineID;
45        lineControls.dwControl = ctrlType;
46        lineControls.cControls = 1;
47        lineControls.cbmxctrl = mcSize;
48
49        // Allocate a buffer for the control
50        mixerControl.cbStruct = mcSize;
51
52        // Get the control
53        details = PCWin32.mixerGetLineControlsA(i, ref lineControls, VolumeConstants.MIXER_GETLINECONTROLSF_ONEBYTYPE);
54
55        //once again check to see if we received any errors
56        if (VolumeConstants.MMSYSERR_NOERROR == details)
57        {
58            bReturn = true;
59            //Copy the control into the destination structure
60            mixerControl = (VolumeStructs.Mixer)Marshal.PtrToStructure(lineControls.pamxctrl, typeof(VolumeStructs.Mixer));
61        }
62        else
63        {
64            bReturn = false;
65        }
66
67        int mcDetailsSize = Marshal.SizeOf(typeof(VolumeStructs.MixerDetails));
68        int mcDetailsUnsigned = Marshal.SizeOf(typeof(VolumeStructs.UnsignedMixerDetails));
69        mcDetails.cbStruct = mcDetailsSize;
70        mcDetails.dwControlID = mixerControl.dwControlID;
71        mcDetails.paDetails = Marshal.AllocCoTaskMem(mcDetailsUnsigned);
72        mcDetails.cChannels = 1;
73        mcDetails.item = 0;
74        mcDetails.cbDetails = mcDetailsUnsigned;
75        details = PCWin32.mixerGetControlDetailsA(i, ref mcDetails, VolumeConstants.MIXER_GETCONTROLDETAILSF_VALUE);
76        detailsUnsigned = (VolumeStructs.UnsignedMixerDetails)Marshal.PtrToStructure(mcDetails.paDetails, typeof(VolumeStructs.UnsignedMixerDetails));
77        currVolume = detailsUnsigned.dwValue;
78        return bReturn;
79    }
80
81    bReturn = false;
82    return bReturn;
83}


Next we will be looking at the SetMixer method. This is the method that does all the work for changing the volume level. It is called from the SetVolume method. We will be passing this method the mixer control we're using, the level we want the volume set at:

01/// <summary>
02/// method for setting the value for a volume control
03/// </summary>
04/// <param name="i"></param>
05/// <param name="mixerControl"></param>
06/// <param name="volumeLevel"></param>
07/// <returns>true/false</returns>
08private static bool SetMixer(int i, VolumeStructs.Mixer mixerControl, int volumeLevel)
09{
10    //method level variables
11    bool bReturn;
12    int details;
13
14    //create our struct object for controlling the system sound
15    VolumeStructs.MixerDetails mixerDetails = new VolumeStructs.MixerDetails();
16    VolumeStructs.UnsignedMixerDetails volume = new VolumeStructs.UnsignedMixerDetails();
17
18    //set out mixer control properties
19    mixerDetails.item = 0;
20    //set the id of the mixer control
21    mixerDetails.dwControlID = mixerControl.dwControlID;
22    //return the size of the mixer details struct
23    mixerDetails.cbStruct = Marshal.SizeOf(mixerDetails);
24    //return the volume
25    mixerDetails.cbDetails = Marshal.SizeOf(volume);
26
27    //Allocate a buffer for the mixer control value buffer
28    mixerDetails.cChannels = 1;
29    volume.dwValue = volumeLevel;
30
31    //Copy the data into the mixer control value buffer
32    mixerDetails.paDetails = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(VolumeStructs.UnsignedMixerDetails)));
33    Marshal.StructureToPtr(volume, mixerDetails.paDetails, false);
34
35    //Set the control value
36    details = PCWin32.mixerSetControlDetails(i, ref mixerDetails, VolumeConstants.MIXER_SETCONTROLDETAILSF_VALUE);
37
38    //Check to see if any errors were returned
39    if (VolumeConstants.MMSYSERR_NOERROR == details)
40    {
41        bReturn = true;
42    }
43    else
44    {
45        bReturn = false;
46    }
47    return bReturn;
48
49}


Now before you can set the volume you need to know what the current volume is, that is the job of our GetVolume method. Here we will call our GetMixer method which will allow us to grab the current volume level. Remember to always close your mixer object when you are done using it to free up those resources, and to prevent any memory leaks.

NOTE: .Net languages are managed languages and do a pretty good job managing resources and memory usage, but here we are dealing with an unmanaged type so we need to ensure we are closing items when we dont need them anymore.

Now for the GetVolume method:

01/// <summary>
02/// method for retrieving the current volume from the system
03/// </summary>
04/// <returns>int value</returns>
05public static int GetVolume()
06{
07    //method level variables
08    int currVolume;
09    int mixerControl;
10
11    //create a new volume control
12    VolumeStructs.Mixer mixer = new VolumeStructs.Mixer();
13     
14    //open the mixer
15    PCWin32.mixerOpen(out mixerControl, 0, 0, 0, 0);
16
17    //set the type to volume control type
18    int type = VolumeConstants.MIXERCONTROL_CONTROLTYPE_VOLUME;
19
20    //get the mixer control and get the current volume level
21    GetMixer(mixerControl, VolumeConstants.MIXERLINE_COMPONENTTYPE_DST_SPEAKERS, type, out mixer, out currVolume);
22
23    //close the mixer control since we are now done with it
24    PCWin32.mixerClose(mixerControl);
25
26    //return the current volume to the calling method
27    return currVolume;
28}


The final method we have is the method for setting the volume to a specified level. Here we will create a new mixer control (as we do in every method in this class, because we make sure to close it as soon as we're done with it). We will then open the mixer, then we will check the value that is being passed for the volume level. If a value greater than the maximum level we will set the level at the maximum value, same with the minimum level, if the value provided is lower than the minimum value we will set the volume level at the minimum level. Once we are done we, once again, close the mixer to free up those resources:

01/// <summary>
02/// method for setting the volume to a specific level
03/// </summary>
04/// <param name="volumeLevel">volume level we wish to set volume to</param>
05public static void SetVolume(int volumeLevel)
06{
07    try
08    {
09        //method level variables
10        int currVolume;
11        int mixerControl;
12
13        //create a new volume control
14        VolumeStructs.Mixer volumeControl = new VolumeStructs.Mixer();
15
16        //open the mixer control
17        PCWin32.mixerOpen(out mixerControl, 0, 0, 0, 0);
18
19        //set the type to volume control type
20        int controlType = VolumeConstants.MIXERCONTROL_CONTROLTYPE_VOLUME;
21
22        //get the current mixer control and get the current volume
23        GetMixer(mixerControl, VolumeConstants.MIXERLINE_COMPONENTTYPE_DST_SPEAKERS, controlType, out volumeControl, out currVolume);
24
25        //now check the volume level. If the volume level
26        //is greater than the max then set the volume to
27        //the max level. If it's less than the minimum level
28        //then set it to the minimun level
29        if (volumeLevel > volumeControl.lMaximum)
30        {
31            volumeLevel = volumeControl.lMaximum;
32        }
33        else if (volumeLevel < volumeControl.lMinimum)
34        {
35            volumeLevel = volumeControl.lMinimum;
36        }
37
38        //set the volume
39        SetMixer(mixerControl, volumeControl, volumeLevel);
40
41        //now re-get the mixer control
42        GetMixer(mixerControl, VolumeConstants.MIXERLINE_COMPONENTTYPE_DST_SPEAKERS, controlType, out volumeControl, out currVolume);
43
44        //make sure the volume level is equal to the current volume
45        if (volumeLevel != currVolume)
46        {
47            throw new Exception("Cannot Set Volume");
48        }
49
50        //close the mixer control as we are finished with it
51        PCWin32.mixerClose(mixerControl);
52    }
53    catch (Exception ex)
54    {
55        MessageBox.Show(ex.Message);
56    }           
57}


Now that we have created this class library you're probably wondering how you actually use it. Well here is an example of how you would use this in, say the click event of a button on your form. When we click the button we will first display the current volume level, we will then set a new volume level, then we will re-display the current volume level:

01private void button1_Click(object sender, System.EventArgs e)
02{
03    //first we will display the current volume
04    Label1.Text = VolumeControl.GetVolume.ToString();
05
06    //now we will change the volume level
07    VolumeControl.SetVolume(50);
08
09    //now we will display the new volume level
10    Label1.Text = VolumeControl.GetVolume().ToString();
11}


There you have it! A way to create a Windows mixer control and control the volume of the computer the application is running on. I truly hope you found this tutorial useful and informative, I know I learned a lot when creating this class library. I am including the solution for this class library, all the license information and headers must remain in tact because it is convered by the GNU - General Public License, but you are free to modify and distribute as you wish. Thank you for reading.

c sharp facebook API

To begin using Facebook APIs, one should start a FacebookService giving it the application API (refer to Background section). Also, according to the application, some user permissions may be needed to be acquired. To get a list of permissions, you can go to http://developers.facebook.com/docs/authentication/permissions.
 // The application key of the Facebook application used
 fbService.ApplicationKey = "";

 // Add all needed permissions
 List<Enums.ExtendedPermissions> perms = new List<Enums.ExtendedPermissions>
                                           {
                                                 Enums.ExtendedPermissions.none
                                           };
 fbService.ConnectToFacebook(perms); 
 
 
Important note: Some permissions are not yet listed in the current SDK, so I sometimes need to add them in the Enums.ExtendedPermissions class and re-compile the source.
After a successful initialization of the FacebookService, running the application now shall result in the following dialog that is used to start a session between a user and Facebook servers.


FB_Login.png Now for the fun stuff. I used the Facebook APIs asynchronously due to the latency that may be noticed due to network issues. It goes like that...
For publishing, the main function used here is Stream.PublishAsync. All I have done is write a neat interface to use this function along with the required callback (a function that is called when the asynchronous result is received successfully).

Source code :
 public void PublishToAFriendWall()
        {
            try
            {
                attachment att = new attachment
                {
                    // Name of link
                    name = "",
                    // URL of link
                    href = "",
                    caption = "",
                    media = new List<attachment_media>()
                };

                attachment_media_image attMEd = new attachment_media_image
                {
                    // Image source
                    src = "",
                    // URL to go to if clicked
                    href = ""
                };
                att.media.Add(attMEd);

                action_link a = new action_link
                {
                    text = "What's this",
                    //URL to go to if clicked
                    href = ""
                };
                IList<action_link> tempA = new List<action_link> { a };

                // Use the typed friend UID to publish the typed message
                fbService.Stream.PublishAsync(friendWallTextBox.Text, att, 
   tempA, uidTextBox.Text, 0, PublishAsyncCompleted, null);
            }
            catch (Exception)
            {

            }
        }

        private static void PublishAsyncCompleted(string result, Object state, 
  FacebookExeption e)
        {

        } 
For the other functionalities, the Facebook APIs used are:
  • Photos.CreateAlbumAsync for creating albums asynchronously
  • Photos.UploadAsync for uploading photos asynchronously
  • Photos.AddTag for tagging photos
  • And for the adding issue, I used the Internet Explorer DLL file (refer to Background section) to pop up a controlled Internet Explorer window showing the page http://www.facebook.com/addfriend.php?id= appended to it the uid of the user to add as a friend.
Mentioning on this article how exactly to use the above APIs is a bit frustrating (240 lines of code!!), so please refer to the attached project. It shows how exactly to use each and every API with the required objects and callbacks.

c sharp screen off

9kop
Screen on/off is a application Build in C#. Using this one application you can turn off your screen  by moving mouse your screen will be on again.
NOTE: Using Laptop you may notice that  it’s a bit difficult to turn off monitor only some time you may run out of battery in laptops and still need to complete your download. you can build your own application in c# to just turn off laptop monitor.
Source Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

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


        private const int WmSyscommand = 0x0112;
        private const int ScMonitorpower = 0xF170;
        private const int HwndBroadcast = 0xFFFF;
        private const int ShutOffDisplay = 2;

        [DllImport("user32.dll")]
        private static extern void LockWorkStation();
        [DllImport("user32.dll", SetLastError = true)]
    private static extern bool PostMessage(IntPtr hWnd, uintmsg,
                      IntPtr wParam, IntPtr lParam);
private static void ScreenOff()
 {
   PostMessage((IntPtr)HwndBroadcast, (uint)WmSyscommand,
            (IntPtr)ScMonitorpower, (IntPtr)ShutOffDisplay);
        }

      private void button1_Click(object sender, EventArgs e)
        {
            ScreenOff();
        }
    }
}

C# Radio Streaming (Bug Fixed)

 
radio
Here is a simple Tutorial for Streaming Radio on internet Trough Sharp Windows form application. First of all  create a new project  by Clicking on File > NewProject>Windows Form application. Name your project and click on ok. Now customize your form as per your needs.Now you have to add a Wmpalyer (Windows Media Player )to your Form. For this You have to add a Reference in your project.
er_diagram
Now you have to if you have a look on the above Image i have 5 Radio buttons.
  • Radio Pakistan
  • Radio Buraq
  • Radio Sama
  • Hum FM
  • Bollywood Masti
Now  You have to set URL of each radio  station  to start Streaming Trough Windows Media Player.
Radio Stations used in this Program are as follow
  • Radio Pakistan URL =http://193.218.160.20:80/kismat/
  • Radio Buraq URL = http://38.96.148.106:8088/
  • Radio Sama URL=http://38.96.148.106:8098/;stream.nsv
  • Radio HUM FM URL=mms://65.19.131.153/humfm-humfm-32
  • Radio Bollywood  Masti URL=http://50.7.70.66:8485/
Now on form load Event Set which radio station you want to  stream(play) by using if condition  as follow.
if(radio_pakistan.Checked=true)
{
   wmp.Url="http://193.218.160.20:80/kismat/ ";


} else if (radio_buraq.Checked)

{
     wmp.URL= http://38.96.148.106:8088/;

} else if(radio_sama.Checked)
{
    wmp.URL=http://38.96.148.106:8098/;stream.nsv;

}  else if (Radio_humFm.Checked)

{
   wmp.URL=mms://65.19.131.153/humfm-humfm-32;

} else if(radio_BM.Checked)

{

 wmp.URL=http://50.7.70.66:8485/;

}

Now run your program, Go trough all radio buttons to check its working or not before  deploying your application.




c sharp Transparent Windows Form

 
Using C#  you can have a transparent Form by using the following program. the following code is called in Form load event of windows form.

Soruce Code :


 private void Myform_Load(object sender, EventArgs e)
        {

            this.TransparencyKey = Color.Black;
            this.BackColor = Color.Black;
        }

c sharp Usb Ports Enable\Disable program

Using C# Program  you can control usb ports in system . if you want to disable All ports of  your system you can use the following program for the this task.
Example 1 :



Above is a snapshot of  application Developed in C# for enabling and disabling Usb ports of a system.
you can develop your own Program like this just do as directed following
Getting start :
first create your project in Visual Studio and name it what ever you want now  Design your form and start coding as following:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace UsbProgram
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

       

      

        private void lockbtn_Click(object sender, EventArgs e)
        {
                           // Create and name your button on form as lockbtn

            try
            {

                string path = "SYSTEM\\CurrentControlSet\\services\\USBSTOR\\";
                RegistryKey RK = Registry.LocalMachine.OpenSubKey(path, true);

                RK.SetValue("Start", "4", RegistryValueKind.DWord);
                status.Text = "Status : All Usb Ports Locked !";
            }
            catch (Exception ex)
            {

                 MessageBox.Show(" Should be Run as Adminstrator","Stop");
            
            }
        }

        private void unlockbtn_Click(object sender, EventArgs e)
        {
            //Name your unlock button as unlockbtn

            status.Text = "Status : All Usb Ports Unlocked !";
            string path = "SYSTEM\\CurrentControlSet\\services\\USBSTOR\\";
            RegistryKey RK = Registry.LocalMachine.OpenSubKey(path, true);

            RK.SetValue("Start", "3", RegistryValueKind.DWord);
        }

       
       
    }
}

c sharp sms gate way

Now you can send   sms directly from your desktop using C#. Just connect your GSM modem to your computer and use the following  code to build Your own sms software.

Now  to build your own SMS software using visual studio in C# Just follow the following steps carefully.

Adding Namespaces:
using System.IO;
using System.IO.Ports;

///////////-Your Form Load Event-///////////////////////////

try

            {

                #region Display all available COM Ports

                string[] ports = SerialPort.GetPortNames();



                // Add all port names to the combo box:

                foreach (string port in ports)

                {

                    this.cboPortName.Items.Add(port);

                }

                #endregion



                //Remove tab pages

                this.tabSMSapplication.TabPages.Remove(tbSendSMS);

                this.tabSMSapplication.TabPages.Remove(tbReadSMS);

                this.tabSMSapplication.TabPages.Remove(tbDeleteSMS);



                this.btnDisconnect.Enabled = false;

            }

            catch(Exception ex)

            {

                ErrorLog(ex.Message);

            }



//////////////-Connecting to GSM Modem-///////

try

            {

                //Open communication port 

                this.port = objclsSMS.OpenPort(this.cboPortName.Text, Convert.ToInt32(this.cboBaudRate.Text), Convert.ToInt32(this.cboDataBits.Text), Convert.ToInt32(this.txtReadTimeOut.Text), Convert.ToInt32(this.txtWriteTimeOut.Text));



                if (this.port != null)

                {

                    //this.tabSMSapplication.TabPages.Remove(tbPortSettings);

                    this.gboPortSettings.Enabled = false;



MessageBox.Show("Modem is connected at PORT " + this.cboPortName.Text,"Free Csharp Tutorials.blogspot.Com");



                    //Add tab pages

                    this.tabSMSapplication.TabPages.Add(tbSendSMS);

                    this.tabSMSapplication.TabPages.Add(tbReadSMS);

                    this.tabSMSapplication.TabPages.Add(tbDeleteSMS);



                    this.lblConnectionStatus.Text = "Connected at " + this.cboPortName.Text;

                    this.btnDisconnect.Enabled = true;

                }



                else

                {

                    MessageBox.Show("Invalid port settings");

                }

            }

            catch (Exception ex)

            {

                ErrorLog(ex.Message);

            }

/////////-Disconnecting GSM Modem-////////////////////////





try

            {

                this.gboPortSettings.Enabled = true;

                objclsSMS.ClosePort(this.port);



                //Remove tab pages

                this.tabSMSapplication.TabPages.Remove(tbSendSMS);

                this.tabSMSapplication.TabPages.Remove(tbReadSMS);

                this.tabSMSapplication.TabPages.Remove(tbDeleteSMS);



                this.lblConnectionStatus.Text = "Not Connected";

                this.btnDisconnect.Enabled = false;



            }

            catch (Exception ex)

            {

                ErrorLog(ex.Message);

            }









//////-Sending MSG -//////////////////////////////////////





  try

            {



                if (objclsSMS.sendMsg(this.port, this.txtSIM.Text, this.txtMessage.Text))

                {

                    MessageBox.Show("Message has sent successfully");

                }

                else

                {

                    MessageBox.Show("Failed to send message");

                }

                

            }

            catch (Exception ex)

            {

                ErrorLog(ex.Message);

            }

        }

        private void btnReadSMS_Click(object sender, EventArgs e)

        {

            try

            {

                //count SMS 

                int uCountSMS = objclsSMS.CountSMSmessages(this.port);

                if (uCountSMS > 0)

                {

                    // If SMS exist then read SMS

                    #region Read SMS

            

                    objShortMessageCollection = objclsSMS.ReadSMS(this.port);

                    foreach (ShortMessage msg in objShortMessageCollection)

                    {



                        ListViewItem item = new ListViewItem(new string[] { msg.Index ,msg.Sender, msg.Message });

                        item.Tag = msg;

                        lvwMessages.Items.Add(item);



                    }

                    #endregion

                }

                else

                {

                    lvwMessages.Clear();

                    MessageBox.Show("There is no message in SIM");



                    

                }

            }

            catch (Exception ex)

            {

                ErrorLog(ex.Message);

            }

        }





//////////////////////// Reading SMS ///////////////////////////////



try

            {

                //count SMS 

                int uCountSMS = objclsSMS.CountSMSmessages(this.port);

                if (uCountSMS > 0)

                {

                    // If SMS exist then read SMS

                    #region Read SMS

  

                    objShortMessageCollection = objclsSMS.ReadSMS(this.port);

                    foreach (ShortMessage msg in objShortMessageCollection)

                    {



                        ListViewItem item = new ListViewItem(new string[] { msg.Index ,msg.Sender, msg.Message });

                        item.Tag = msg;

                        lvwMessages.Items.Add(item);



                    }

                    #endregion

                }

                else

                {

                    lvwMessages.Clear();

                    MessageBox.Show("There is no message in SIM");



                    

                }



///////////////////////////////////-Deleting SMS From Modem SIM-/////////////////////////



try

            {

                //Count SMS 

                int uCountSMS = objclsSMS.CountSMSmessages(this.port);

                if (uCountSMS > 0)

                {

                    DialogResult dr = MessageBox.Show("Are u sure u want to delete the SMS?", "Delete confirmation", MessageBoxButtons.YesNo);



                    if (dr.ToString() == "Yes")

                    {

                        #region Delete SMS



                        if (this.rbDeleteAllSMS.Checked)

                        {                           

                    



                            #region Delete all SMS

                            string strCommand = "AT+CMGD=1,4";

                            if (objclsSMS.DeleteMsg(this.port, strCommand))

                            {

                                MessageBox.Show("Messages has deleted successfuly ");

                            }

                            else

                            {

                                MessageBox.Show("Failed to delete messages ");

                            }

                            #endregion

                            

                        }

                        else if (this.rbDeleteReadSMS.Checked)

                        {                          

                            //...............................................Delete Read SMS ....................................................



                            #region Delete Read SMS

                            string strCommand = "AT+CMGD=1,3";

                            if (objclsSMS.DeleteMsg(this.port, strCommand))

                            {

                                MessageBox.Show("Messages has deleted successfuly ");

                            }

                            else

                            {

                                MessageBox.Show("Failed to delete messages ");

                            }

                            #endregion



                        }



                        #endregion

                    }

                }

            }

            catch (Exception ex)

            {

                ErrorLog(ex.Message);

            }



        }

        private void btnCountSMS_Click(object sender, EventArgs e)

        {

            try

            {

                //Count SMS

                int uCountSMS = objclsSMS.CountSMSmessages(this.port);

                this.txtCountSMS.Text = uCountSMS.ToString();

            }

            catch (Exception ex)

            {

                ErrorLog(ex.Message);

            }

        }





//////////////////////////////////////-Error Log -////////////////////////



  public void ErrorLog(string Message)

        {

            StreamWriter sw = null;



            try

            {

                string sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";

                string sPathName = @"E:\";



                string sYear = DateTime.Now.Year.ToString();

                string sMonth = DateTime.Now.Month.ToString();

                string sDay = DateTime.Now.Day.ToString();



                string sErrorTime = sDay + "-" + sMonth + "-" + sYear;



                sw = new StreamWriter(sPathName + "SMSapplication_ErrorLog_" + sErrorTime + ".txt", true);



                sw.WriteLine(sLogFormat + Message);

                sw.Flush();



            }

            catch (Exception ex)

            {

                ErrorLog(ex.ToString());

            }

            finally

            {

                if (sw != null)

                {

                    sw.Dispose();

                    sw.Close();

                }

            }





        }

        #endregion 

    

    }

}


Sending SMS Via Windows Form Application Using any Android Smart Phone  Source Code  using System ; using System . C...