C#-windows-Forms-part1

Windows Forms Agenda:

1. Basic Controls
2. Panels and Layouts
3. Drawing and GDI Devices
4. MenuStrip, ToolStrip and ContextMenuStrip
5. Model and Modeless Dialog boxes
6. Multiple Document Interface (MDI)
7. Form Inheritance
8. Building Login Form
9. Working with Resource Files and Settings
10. Notify Icon Controls
11. Using Components like Timer, FileSystemWatcher, Process, BackgroundWorker
12. Drag and Drop
13. Working with Advanced controls like TreeView and ListView

Window Forms:

WinForms = Controls + Graphics Used for Developing Rich GUI Application.
 Important Properties of Controls:
  • Control Properties: Dock, Anchor
  • Label Properties: Text, Image, AutoSize, UseMnemonic
  • PictureBox Properties: Image, SizeMode (Normal / StretchImage / AutoSize / CenterImage / Zoom)
  • LinkLabel Properties: Text, LinkVisited, LinkColor, VisitedLinkColor, ActiveLinkColor, DisableLinkColor

Using Link Label :

Private Sub linkLabel1_Click(. . .)

Handles linkLabel1.Click System.Diagnostics.Process.Start(“c:\demo.html”)
End Sub 

Using Link Label:

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) 
                { 
               system.Diagnostics.Process.Start(“c:\\demo.html“);
       } 
 
TextBox :

Properties: Text, PasswordChar, Multiline, Readonly, AutoCompleteMode, AutoCompleteSource, AutoCompleteCustomSource
Events: KeyPress, KeyDown, TextChanged, Validating

AutoComplete Example:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim names() As String = New String() {“deccan”, “deccansoft”, “deccan chronical”, “testing”, “demo”} Dim sc As AutoCompleteStringCollection = New AutoCompleteStringCollection
For Each name As String In names
sc.Add(name)
Next
txtDemo.AutoCompleteCustomSource = sc
txtDemo.AutoCompleteSource = AutoCompleteSource.CustomSource
End Sub

AutoComplete Example:

private void Form1_Load(object sender, EventArgs e)
{
 string[] names = { “deccan”, “deccansoft”, “deccan chronical”, “testing”, “demo” }; AutoCompleteStringCollection sc = new AutoCompleteStringCollection();
 foreach (string name in names)
sc.Add(name);
txtDemo.AutoCompleteCustomSource = sc;
txtDemo.AutoCompleteSource = AutoCompleteSource.CustomSource;
}

Note:

  • In KeyDown we cannot distinguish upper and lower case characters.
  • KeyPress event fires only for keys with ASCII value where as KeyDown event fires for all keys on the keyboard.

Using KeyPress:

Private Sub TextBox1_KeyPress

(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress ‘MessageBox.Show(((int)e.KeyChar).ToString());
If (CType(e.KeyChar, Integer) = 8) Then
 Return 
End If 
If ((e.KeyChar < Microsoft.VisualBasic.ChrW(48)) _
OrElse (e.KeyChar > Microsoft.VisualBasic.ChrW(57))) Then
e.Handled = True
End If 
‘Don_t display the char in textbox.
End Sub
Private Sub

TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

If (e.Control AndAlso (e.KeyCode = Keys.A)) Then 
MessageBox.Show(“Control + A is Clicked”)
End If 
End Sub
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVale As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If (txtDemo.Text = “”) Then
errorProvider1.SetError(txtDemo, “The value cannot be empty”)
e.Cancel = True 
‘Doesn_t allow the textbox to lose focus. 
Else
errorProvider1.SetError(txtDemo, “”)
End If
 End Sub

Using KeyPress:

private void txtDemo_KeyPress(object sender, KeyPressEventArgs e)
{
//MessageBox.Show(((int)e.KeyChar).ToString());
if ((int)e.KeyChar == 8) //for backspace
return;
 if (e.KeyChar < ‘0’ || e.KeyChar > ‘9’) //If the Char is in range of 48 to 57.
e.Handled = true; //Don’t display the char in textbox.
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
 if (e.Control && e.KeyCode == Keys.A)
MessageBox.Show(“Control + A is Clicked”);
}
//To validate the content of the textbox before the focus is lost from it: 
private void txtDemo_Validating(object sender, CancelEventArgs e)
{
if (txtDemo.Text == “”)
{
errorProvider1.SetError(txtDemo, “The value cannot be empty”);
e.Cancel = true; //Doesn’t allow the textbox to lose focus.
}
else 
errorProvider1.SetError(txtDemo, “”);
}

Note: ErrorProvider is in ComponentsTab in Toolbox

Button:
Button Properties: CausesValidation

Form Properties: AcceptButton, CancelButton (to be used in context of button)

CheckBox:

Properties: Text, Checked, ThreeState, CheckState (Checked/UnChecked/Intermediate)
Events: CheckedChanged.

RadioButton:
To group we have to use a common container which can be either Form or Group Box or Panel.
ComboBox
Properties: Items, DropDownStyle (Simple/DropDownList/DropDown), Text, SelectedIndex, SelectedItem
Events: SelectedIndexChanged

Combobox Example

Class Student
Public Id As Integer
Public Name As String
Public Sub New(ByVal id As Integer, ByVal name As String)
MyBase.New()
id = id
name = name
End Sub 
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Private Sub DemoForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmbStudent.Items.Add(new Student(1, “S1”));
cmbStudent.Items.Add(new Student(2, “S2”));
cmbStudent.Items.Add(new Student(3, “S3”));
cmbStudent.Items.Add(new Student(4, “S4”));
End Sub 
Private Sub cmbStudent_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbStudent.SelectedIndexChanged
Dim s As Student = CType(cmbStudent.SelectedItem, Student)
MessageBox.Show(s.Id.ToString)
End Sub

 Combobox Example
 class Student //Write outside the Form Class. 

public int Id; 
public string Name; 
public Student(int id, string name)
 {
Id = id; 
Name = name; 

public override string ToString() 

return Name;
 } 

private void DemoForm_Load(object sender, EventArgs e) 

cmbStudent.Items.Add(new Student(1, “S1”));
cmbStudent.Items.Add(new Student(2, “S2”));
cmbStudent.Items.Add(new Student(3, “S3”));
cmbStudent.Items.Add(new Student(4, “S4”)); 

private void cmbStudent_SelectedIndexChanged (object sender, EventArgs e) 

Student s = (Student)cmbStudent.SelectedItem; 
MessageBox.Show(s.Id.ToString()); 

Note: To a ComboBox any type of object can be added. The ToString() implementation of that objects will be displayed as the Items text in the ComboBox.

DateTimePicker:
Properties: Value, MinDate, MaxDate, ShowCheckBox, Checked, ShowUpDown, Format,
CustomFormat (dd/MM/yyyy hh:mm:ss tt) – Only if Format = “Custom”


Events: ValueChanged

MonthCalander:
Properties: CalanderDimension.Width / Height, SelectionRange.Start /.End, ShowWeekNumbers
Events: DateChanged

MaskedTextBox:
Properties: Text, Mask, PromptChar

Containers

  • Panel
  • GroupBox
  • FlowLayoutPanel
  • TableLayoutPanel
  • TabControl
  • SplitContainer

Click here for: Free C# Essential training videos for beginners | Online C# training with project

 



 

 

Sample Programs in VB

Sample Programs in VB

Program to check the range of a datatype

Public Class Max_Min_Values
Public Shared Sub Main()
Console.WriteLine(Integer.MaxValue)
Console.WriteLine(Integer.MinValue)
Console.WriteLine(Double.MaxValue)
Console.WriteLine(Double.MinValue)
End Sub
End Class

Prog to demonstrate In-Built AscW and ChrW Functions:

Class GetAscii
Shared Sub Main()
Dim str As String = Console.ReadLine()
Dim ch As Char = CChar(str)
Dim n As Integer = AscW(ch)
Console.WriteLine(n)
End Sub
End Class

Program to demonstrate If Statement

Public Class IfDemo
Shared Sub Main()
Dim a, b, c As Integer
Console.WriteLine("Enter 3 Numbers")
a = Integer.Parse(Console.ReadLine())
b = Integer.Parse(Console.ReadLine())
c = Integer.Parse(Console.ReadLine())
Dim max As Integer = a
If (b > max) Then max = b
If (c > max) Then max = c
Console.WriteLine("Greatest No is " & max)
End Sub
End Class

Class IfDemo2

Public Shared Sub Main(ByVal args() As String)
If (args.Length = 0) Then
Console.WriteLine("Please provide a number")
ElseIf (Not Integer.TryParse(args(0), 0)) Then
Console.WriteLine("Not a number")
ElseIf (Integer.Parse(args(0)) Mod 2 = 0) Then
Console.WriteLine("Even number")
Else
Console.WriteLine("Odd number")
End If
End Sub
End Class

Program to demonstrate Select statement

Public Class SelectDemo
Shared Sub Main()
Dim grade As String
Console.WriteLine("Enter a grade")
grade = Console.ReadLine()
Select Case (grade)
Case "E" , "e"
Console.WriteLine("Excellent")
Case "G" , "g"
Console.WriteLine("Good")
Case Else
Console.WriteLine("No Such Grades")
End Select
End Sub
End Class
Public Class SelectCases
Shared Sub Main()
Dim n As Integer
Console.WriteLine("Enter a Number")
n = Integer.Parse(Console.ReadLine())
Select Case (n)
Case 1
Console.WriteLine("Case 1")
Case 2, 3
Console.WriteLine("Case 2,3")
Case 4 To 7
Console.WriteLine("Case 4 To 7")
Case Is < 9
Console.WriteLine("Case Is < 9") Case Is > 9
Console.WriteLine("Case Is > 9")
End Select
End Sub
End Class

Program to demonstrate While loop

Public Class WhileDemo
Shared Sub Main()
Dim marks, count, total As Integer
Dim avg as Double
Console.WriteLine("Enter 6 Subject marks")
While (count < 6)
marks = Integer.Parse(Console.ReadLine())
total += marks
count += 1
End While
avg = total / 6
Console.WriteLine("Total is " & total)
Console.WriteLine("Average is " & avg)
End Sub
End Class

Program to demonstrate While loop

Public Class WhileDemo
Shared Sub Main()
Dim marks, count, total As Integer
Dim avg as Double
Console.WriteLine("Enter 6 Subject marks")
While (count < 6)
marks = Integer.Parse(Console.ReadLine())
total += marks
count += 1
End While
avg = total / 6
Console.WriteLine("Total is " & total)
Console.WriteLine("Average is " & avg)
End Sub
End Class

Program to generate table using For loop

Class Table
Shared Sub Main()
Dim n As Integer
Console.Write("Table of: ")
n = Integer.Parse(Console.ReadLine())
Dim s As String = ""
For i As Integer = 1 To 10
s &= n & "*" & i & "=" & n * i & vbCrLf
Next
Console.WriteLine(s)
End Sub
End Class

Program to print a range of numbers

Dim m, n, incr As Integer
Console.Write("Enter Starting Number: ")
m = Integer.Parse(Console.ReadLine())
Console.Write("Enter Ending Number: ")
n = Integer.Parse(Console.ReadLine())
Console.Write("Increment By: ")
incr = Integer.Parse(Console.ReadLine())
For i As Integer = m To n Step incr
Console.WriteLine(i)
Next i

Program to generate a triangle using For loop

Class Triangle
Public Shared Sub Main()
For i As Integer = 1 To 10
For j As Integer = 1 To i
Console.Write("*" & " ")
Next
Console.WriteLine()
Next
Dim n, m, o As Integer
For n = 10 To 1 Step -1
For o = 0 To n - 1
Console.Write(" ")
Next
For m = n To 10
Console.Write("* ")
Next
Console.WriteLine()
Next
End Sub
End Class

Class PalindromeProgram
Shared Sub Main(ByVal args As String())
Dim str As String
str = Console.ReadLine()
Dim n As Integer = str.Length
For i As Integer = 0 To n \ 2
If (str(i) <> str(n – i – 1)) Then
Console.WriteLine(“Its not a palindrome”)
Return
End If
Next
Console.WriteLine(“Its a palindrome”)
End Sub
End Class

Program to demonstrate Arrays

Public Class Array_Example
Public Shared Sub Main()
Dim ar() As Integer = {1, 2, 3, 4, 5}
Console.WriteLine(ar.Length)
For Each tmp As Integer In ar
Console.WriteLine(tmp)
Next
ReDim ar(10)
For Each tmp As Integer In ar
Console.WriteLine(tmp)
Next
End Sub
End Class

Program to demonstrate Arrays and Array class

Class Program
Shared Sub Main()
Dim ar(-1) As Integer
While (True)
Select Case GetOption()
Case 1
ar = CreateArray()
Case 2
Array.Sort(ar)
Case 3
Array.Reverse(ar)
Case 4
PrintArray(ar)
Case 5
Console.WriteLine("Thank you")
Return
Case Else
Console.WriteLine("Invalid option")
End Select
End While
End Sub
Shared Function GetOption() As Integer
Console.WriteLine("1. Create")
Console.WriteLine("2. Sort")
Console.WriteLine("3. Reverse")
Console.WriteLine("4. Print")
Console.WriteLine("5. Exit")
Console.Write("Enter your option: ")
Return Integer.Parse(Console.ReadLine())
End Function
Shared Function CreateArray() As Integer()
Console.Write("Enter the array length: ")
Dim n As Integer
n = Integer.Parse(Console.ReadLine())
Dim ar(n - 1) As Integer
For i As Integer = 0 To n - 1
Console.Write("Enter the " & i & "th value: ")
ar(i) = CInt(Console.ReadLine())
Next
Return ar
End Function
Shared Sub PrintArray(ByVal ar As Integer())
For Each value As Integer In ar
Console.Write(value & " ")
Next
Console.WriteLine()
End Sub
End Class

Multithreading in C Sharp Part1

Multithreading in C# – Threading Overview & Scheduling

Overview of Process and Threads

Process:

  • A process is a running instance of an application.
  • Every process has its own memory address space (execution environment) and it is in that all the data and
    the instructions of that process reside.
  • A process has a self-contained execution environment. A process generally has a complete, private set of
    basic run-time resources; in particular, each process has its own memory space

Thread:

  • The path of execution of instructions within a process is called a thread.
  • It has a starting point, execution sequence and terminating point.

A program with multiple simultaneous paths of execution is said to be multithreaded application.

Multithreading Multiprocessing/Multitasking
Multithreading is the ability of an operating system to execute the different parts of the program,
called threads, concurrently.
Multitasking is the ability of an operating system to accommodate more than one program in the memory at
the same time.
In multithreading all threads share same process address space [memory]. Processes do not share the memory
Threads can share variables since threads are in same process. External resources like file system or database must be used for communication between multiple processes and
each one runs under its unique process address space.
Inter thread communication is simple Inter process communication is complex
Less resources required to launch/run them since they are part of an already running process, hence they are
called as light weight tasks.
CPU has to spend more resources for launching a new process hence process is known as heavy weight.

Types of Scheduling

Preemptive: OS can un-schedule a thread even if it is not completed its task.

Non-Preemptive: OS cannot unschedule the thread. A Thread should either get unscheduled itself or it should
complete its task and release the processor.

  • Scheduling is done based on the priority of the thread. A thread with highest priority is executed in
    the processor. If multiple threads exist with same priority then a time slice is assigned to each thread.
  • In MS-Windows execution of the thread is based on: Preemptive Scheduling –> Priority –> Time slice
  • Also, in all versions of MS Windows, to avoid starvation low priority threads are also executed in the processor
    but the number of times they execute is very less.
  • Switching means that the processor stores the state of the outgoing thread (it does so by noting the current
    processor register values and the last instruction-set the thread was about to perform), restores the state of the
    incoming thread (again by restoring its processor register values and picking the last instruction-set where it had
    left itself) and then runs it.

Note: On a multi-processor system, the operating system can allocate individual threads to the separate
processors, which thus fastens the execution of the program. The efficiency of the threads also increases
significantly because the distribution of the threads on several processors is faster than sharing time-slices
on a single processor. It is particularly useful to have a multi-processor system for 3D modeling and image-processing.

Example of some Multithreading Applications:

  1. MS-Word – Auto Saving, Spell Checking, Printing while editing
  2. VS.NET – Intellisense, Auto Compilation.
  3. Browser – Downloading multiple files and browsing simultaneously.
  4. Media Player – Movie and Sound

For Complete C# Online training with material