14.introducere in windows forms
DESCRIPTION
.netTRANSCRIPT
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
Windows forms
Ceea ce in programarea Windows se numeste o fereastra, in programarea sub .NET se numeste
form. Acest form (aceasta fereastra) este caracterizat de un titlu, optional meniu, toolbar, bare de
navigare si ceea ce ramane se numeste zona client.
Form-urile sunt obiecte ce expun proprietati ce definesc modul de afisare, metode ce definesc
comprtarea si evenimente ce definesc interactiunea cu utilizatorul. Setand proprietatile unui form
si scriind codul ce raspunde la evenimente, in fapt realizam obiecte ce se comporta conform
cerintelor cerute de aplicatie. Form-urile sunt instante ale claselor.
Aplicatiile Windows Forms sunt echivalente cu aplicatiile din MFC bazate pe dialog.
Cel mai scurt program sub Windows poate fi: class Form1 { public static void Main()
{ new System.Windows.Forms.Form();
} }
In mod normal ar trebui sa utilizam spatiul de nume System.Windows.Forms folosind o directiva using.
Clasa Forms este derivata din ContainerControl care la randul ei samd
Cuvantul control este folosit pentru a se referi la obiectele de interfata cum ar fi butoane, bare de
defilare (scroll bars), campuri de editare, etc. Clasa Control implementeaza aspectul vizual al
acestor ferestre, intrarea de la tastatura si intrarea de la mouse, iar fiecare obiect particular
implementeaza particularitatile specifice si stie sa raspunda la mesajele adresate direct sau
indirect.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
In exemplul de mai sus s-a apelat doar ctorul clasei, dar fereastra nu este vizibila (tehnica
asemanatoare din Windows). Pentru a face fereastra vizibila va trebui sa apelam metoda numita
Show() (in Windows avem ShowWindow() si Update()). Deci exemplul de mai sus devine:
using System.Windows.Forms; class ShowForm { public static void Main()
{ Form form = new Form();
form.Show(); }
}
Form mosteneste din Control doua metode: Show() si Hide().
In loc de a apela metoda Show() putem folosi proprietatea Visible ca mai jos: form.Visible = true;
Pentru a schimba (sau obtine) titlul ferestrei (form-ului) folosim proprietatea Text ca mai jos: form.Text = Un nou titlu;
sau
titlu = form.Text.Trim();
ceea ce inseamna ca am eliminat spatiile de la dreapta sirului de caractere ce denumeste titlul
ferestrei.
Proprietatea Text are intelesuri diferite pentru diverse controale: pentru butoane set/get textul butonului, pentru campuri de editare set/get continutul campului, pentru form-uri set/get titlul
(caption).
Pentru a face ca forma sa ramina pe ecran va trebui sa folosim metoda Run() definita in calsa
Application. Toate metodele din aceasta clasa sunt statice. Ca atare exemplul de mai sus poate fi imbunatatit astfel:
using System.Windows.Forms; class Ex1Eronat { public static void Main()
{ Form form = new Form(); form.Text = Not a Good Idea; form.Visible = true; Application.Run()
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
} }
Rezultatul este:
Aceasta versiune are dezavantajul ca o data ce am minimizat fereastra nu o mai putem maximiza.
Metoda Run() nu se aplica unei anumite ferestre in acest caz.
Forma finala ar putea fi:
using System.Windows.Forms; class ExMaiBun { public static void Main()
{ Form form = new Form(); form.Text = Mai bine; form.Visible = true; Application.Run(form)
} }
in care metoda Run() are drept parametru form-ul nostru si nu mai e necesar apelul metodei
Show() sau a proprietatii Visible. Acestea sunt date de metoda Run(). Practic in acest moment bucla de mesaje a aplicatiei este pusa in functiune si aceasta fereastra poate raspunde la
mesaje. Cand inchidem fereastra (form-ul) pasat ca argument in metoda Run() se vor inchide
toate ferestrele create de aceasta aplicatie.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
Form Members MSDN
Folosind proprietatile disponibile din clasa Form, putem determina marimea, culoarea, si putem
gestiona trasaturile ferestrei sau casetei de dialog pe care o cream.
De asemenea putem folosi metodele si putem trata evenimente atasate la form. Toate acestea
sunt descrise in clasa Form.
Exemplu
public void CreateMyForm() { // Create a new instance of the form. Form form1 = new Form(); // Create two buttons to use as the accept and cancel buttons.
Button button1 = new Button (); Button button2 = new Button (); // Set the text of button1 to "OK". button1.Text = "OK"; // Set the position of the button on the form. button1.Location = new Point (10, 10); // Set the text of button2 to "Cancel". button2.Text = "Cancel"; // Set the position of the button based on the location of button1.
button2.Location = new Point (button1.Left, button1.Height + button1.Top + 10); // Set the caption bar text of the form. form1.Text = "My Dialog Box"; // Display a help button on the form. form1.HelpButton = true; // Define the border style of the form to a dialog box. form1.FormBorderStyle = FormBorderStyle.FixedDialog; // Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false; // Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false; // Set the accept button of the form to button1. form1.AcceptButton = button1; // Set the cancel button of the form to button2. form1.CancelButton = button2; // Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen; // Add button1 to the form. form1.Controls.Add(button1); // Add button2 to the form. form1.Controls.Add(button2);
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
// Display the form as a modal dialog box. form1.ShowDialog(); }
Public Constructors
Form Constructor . Initializes a new instance of the Form class.
Public Properties
AcceptButton Gets or sets the button on the form that is
clicked when the user presses the ENTER
key.
ActiveForm Gets the currently active form for this
application.
AutoScale Gets or sets a value indicating whether the
form adjusts its size to fit the height of the
font used on the form and scales its controls.
AutoScroll Overridden. Gets or sets a value indicating
whether the form enables autoscrolling.
AutoScrollMargin (inherited from
ScrollableControl)
Gets or sets the size of the auto-scroll
margin.
AutoScrollMinSize (inherited from
ScrollableControl)
Gets or sets the minimum size of the auto-
scroll.
AutoScrollPosition (inherited from
ScrollableControl)
Gets or sets the location of the auto-scroll
position.
BackColor Overridden. See Control.BackColor.
BackgroundImage (inherited from Control) Gets or sets the background image displayed
in the control.
BindingContext (inherited from Control) Gets or sets the BindingContext for the
control.
(vezi ex. MSDN) protected void BindControls() { /* Create two Binding objects for the first two TextBox controls. The data-bound property for both controls is the Text property. The data source is a DataSet (ds). The data member is a navigation path in the form: "TableName.ColumnName". */ text1.DataBindings.Add(new Binding("Text", ds, "customers.custName")); text2.DataBindings.Add(new Binding("Text", ds, "customers.custID")); /* Bind the DateTimePicker control by adding a new Binding.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
The data member of the DateTimePicker is a navigation path: TableName.RelationName.ColumnName string. */ DateTimePicker1.DataBindings.Add(new Binding("Value", ds, "customers.CustToOrders.OrderDate")); /* Add event delegates for the Parse and Format events to a new Binding object, and add the object to the third TextBox control's BindingsCollection. The delegates must be added before adding the Binding to the collection; otherwise, no formatting occurs until the Current object of the BindingManagerBase for the data source changes. */ Binding b = new Binding("Text", ds, "customers.custToOrders.OrderAmount"); b.Parse+=new ConvertEventHandler(CurrencyStringToDecimal); b.Format+=new ConvertEventHandler(DecimalToCurrencyString); text3.DataBindings.Add(b); // Get the BindingManagerBase for the Customers table. bmCustomers = this.BindingContext [ds, "Customers"]; /* Get the BindingManagerBase for the Orders table using the RelationName. */ bmOrders = this.BindingContext[ds, "customers.CustToOrders"]; /* Bind the fourth TextBox control's Text property to the third control's Text property. */ text4.DataBindings.Add("Text", text3, "Text"); }
CancelButton Gets or sets the button control that is clicked
when the user presses the ESC key.
CanFocus (inherited from Control) Gets a value indicating whether the control
can receive focus.
CanSelect (inherited from Control) Gets a value indicating whether the control
can be selected.
Capture (inherited from Control) Gets or sets a value indicating whether the
control has captured the mouse.
CausesValidation (inherited from Control) Gets or sets a value indicating whether the
control causes validation to be performed on
any controls that require validation when it
receives focus.
ClientRectangle (inherited from Control) Gets the rectangle that represents the client
area of the control.
ClientSize Gets or sets the size of the client area of the
form.
Container (inherited from Component) Gets the IContainer that contains the
Component.
ContainsFocus (inherited from Control) Gets a value indicating whether the control,
or one of its child controls, currently has the
input focus.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
ContextMenu (inherited from Control) Gets or sets the shortcut menu associated
with the control.
ControlBox Gets or sets a value indicating whether a
control box is displayed in the caption bar of
the form.
Controls (inherited from Control) Gets the collection of controls contained
within the control.
Cursor (inherited from Control) Gets or sets the cursor that is displayed when
the mouse pointer is over the control.
DataBindings (inherited from Control) Gets the data bindings for the control.
DialogResult Gets or sets the dialog result for the form.
DisplayRectangle (inherited from Control) Gets the rectangle that represents the display
area of the control.
Disposing (inherited from Control) Gets a value indicating whether the control is
in the process of being disposed of.
Enabled (inherited from Control)
Supported by the .NET Compact Framework.
Gets or sets a value indicating whether the
control can respond to user interaction.
Focused (inherited from Control)
Supported by the .NET Compact Framework.
Gets a value indicating whether the control
has input focus.
Font (inherited from Control) Gets or sets the font of the text displayed by
the control.
ForeColor (inherited from Control) Gets or sets the foreground color of the
control.
FormBorderStyle Gets or sets the border style of the form.
Handle (inherited from Control) Gets the window handle that the control is
bound to.
HasChildren (inherited from Control) Gets a value indicating whether the control
contains one or more child controls.
Height (inherited from Control) Gets or sets the height of the control.
HelpButton Gets or sets a value indicating whether a
Help button should be displayed in the
caption box of the form.
Icon Gets or sets the icon for the form.
InvokeRequired (inherited from Control) Gets a value indicating whether the caller
must call an invoke method when making
method calls to the control because the caller
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
is on a different thread than the one the
control was created on.
IsAccessible (inherited from Control) Gets or sets a value indicating whether the
control is visible to accessibility
applications.
IsDisposed (inherited from Control) Gets a value indicating whether the control
has been disposed of.
KeyPreview Gets or sets a value indicating whether the
form will receive key events before the event
is passed to the control that has focus.
Left (inherited from Control) Gets or sets the x-coordinate of a control's
left edge in pixels.
Location (inherited from Control) Gets or sets the coordinates of the upper-left
corner of the control relative to the upper-left
corner of its container.
MaximizeBox Gets or sets a value indicating whether the
maximize button is displayed in the caption
bar of the form.
MaximumSize Gets the maximum size the form can be
resized to.
Menu Gets or sets the MainMenu that is displayed
in the form.
MinimizeBox Gets or sets a value indicating whether the
minimize button is displayed in the caption
bar of the form.
MinimumSize Gets or sets the minimum size the form can
be resized to.
Modal Gets a value indicating whether this form is
displayed modally.
Name (inherited from Control) Gets or sets the name of the control.
Parent (inherited from Control) Gets or sets the parent container of the
control.
ParentForm (inherited from
ContainerControl)
Gets the form that the container control is
assigned to.
Right (inherited from Control) Gets the distance between the right edge of
the control and the left edge of its container.
RightToLeft (inherited from Control) Gets or sets a value indicating whether
control's elements are aligned to support
locales using right-to-left fonts.
ShowInTaskbar Gets or sets a value indicating whether the
form is displayed in the Windows taskbar.
Site (inherited from Control) Overridden. Gets or sets the site of the
control.
Size Gets or sets the size of the form.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
StartPosition Gets or sets the starting position of the form
at run time.
TabStop (inherited from Control) Gets or sets a value indicating whether the
user can give the focus to this control using
the TAB key.
Tag (inherited from Control) Gets or sets the object that contains data
about the control.
Text (inherited from Control) Gets or sets the text associated with this
control.
Visible (inherited from Control) Gets or sets a value indicating whether the
control is displayed.
Width (inherited from Control) Gets or sets the width of the control.
WindowState Gets or sets the form's window state.
Public Methods
Activate Activates the form and gives it focus.
BringToFront (inherited from Control) Brings the control to the front of the z-order.
Close Closes the form.
Contains (inherited from Control) Retrieves a value indicating whether the
specified control is a child of the control.
Dispose (inherited from Component) Overloaded. Releases the resources used by the
Component.
FindForm (inherited from Control) Retrieves the form that the control is on.
Focus (inherited from Control) Sets input focus to the control.
GetNextControl (inherited from Control) Retrieves the next control forward or back in
the tab order of child controls.
Hide (inherited from Control) Conceals the control from the user.
Invalidate (inherited from Control) Overloaded. Invalidates a specific region of the
control and causes a paint message to be sent to
the control.
PointToClient (inherited from Control) Computes the location of the specified screen
point into client coordinates.
PointToScreen (inherited from Control) Computes the location of the specified client
point into screen coordinates.
PreProcessMessage (inherited from
Control)
Preprocesses input messages within the
message loop before they are dispatched.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
Refresh (inherited from Control) Forces the control to invalidate its client area
and immediately redraw itself and any child
controls.
Select (inherited from Control) Overloaded. Activates a control.
SelectNextControl (inherited from
Control)
Activates the next control.
Show (inherited from Control) Displays the control to the user.
ShowDialog Overloaded. Shows the form as a modal dialog
box.
ToString Overridden. See Object.ToString.
Public Events
Activated Occurs when the form is activated in code or by
the user.
Click (inherited from Control) Occurs when the control is clicked.
Closed Occurs when the form is closed.
Closing Occurs when the form is closing.
Deactivate Occurs when the form loses focus and is not the
active form.
Disposed (inherited from Component) Adds an event handler to listen to the Disposed
event on the component.
DockChanged (inherited from Control) Occurs when the value of the Dock property
changes.
DoubleClick (inherited from Control) Occurs when the control is double-clicked.
DragDrop (inherited from Control) Occurs when a drag-and-drop operation is
completed.
EnabledChanged (inherited from Control) Occurs when the Enabled property value has
changed.
Enter (inherited from Control) Occurs when the control is entered.
GotFocus (inherited from Control) Occurs when the control receives focus.
Invalidated (inherited from Control) Occurs when a control's display requires
redrawing.
KeyDown (inherited from Control) Occurs when a key is pressed while the control
has focus.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
KeyPress (inherited from Control) Occurs when a key is pressed while the control
has focus.
KeyUp (inherited from Control) Occurs when a key is released while the control
has focus.
Layout (inherited from Control) Occurs when a control should reposition its
child controls.
Leave (inherited from Control) Occurs when the input focus leaves the control.
Load Occurs before a form is displayed for the first
time.
LostFocus (inherited from Control) Occurs when the control loses focus.
MenuComplete Occurs when the menu of a form loses focus.
MenuStart Occurs when the menu of a form receives focus.
MouseDown (inherited from Control) Occurs when the mouse pointer is over the
control and a mouse button is pressed.
MouseEnter (inherited from Control) Occurs when the mouse pointer enters the
control.
MouseHover (inherited from Control) Occurs when the mouse pointer hovers over the
control.
MouseLeave (inherited from Control) Occurs when the mouse pointer leaves the
control.
MouseMove (inherited from Control) Occurs when the mouse pointer is moved over
the control.
MouseUp (inherited from Control) Occurs when the mouse pointer is over the
control and a mouse button is released.
MouseWheel (inherited from Control) Occurs when the mouse wheel moves while the
control has focus.
Move (inherited from Control) Occurs when the control is moved.
TextChanged (inherited from Control) Occurs when the Text property value changes.
Validated (inherited from Control) Occurs when the control is finished validating.
Validating (inherited from Control) Occurs when the control is validating.
Protected Properties
Events (inherited from Component) Gets the list of event handlers that are attached
to this Component.
FontHeight (inherited from Control) Gets or sets the height of the font of the control.
HScroll (inherited from Gets or sets a value indicating whether the
horizontal scroll bar is visible.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
ScrollableControl)
MaximizedBounds Gets and sets the size of the form when it is
maximized.
ResizeRedraw (inherited from Control) Gets or sets a value indicating whether the
control redraws itself when resized.
ShowFocusCues (inherited from Control) Gets a value indicating whether the control
should display focus rectangles.
ShowKeyboardCues (inherited from
Control)
Gets a value indicating whether the control
should display keyboard shortcuts.
VScroll (inherited from
ScrollableControl)
Gets or sets a value indicating whether the
vertical scroll bar is visible.
Protected Methods
OnClick (inherited from Control) Raises the Click event.
OnClosed Raises the Closed event.
OnClosing Raises the Closing event.
OnInvalidated (inherited from Control) Raises the Invalidated event.
OnKeyDown (inherited from Control) Raises the KeyDown event.
OnKeyPress (inherited from Control) Raises the KeyPress event.
OnKeyUp (inherited from Control) Raises the KeyUp event.
OnLeave (inherited from Control) Raises the Leave event.
OnLoad Raises the Load event.
OnLostFocus (inherited from Control) Raises the LostFocus event.
OnMaximizedBoundsChanged Raises the MaximizedBoundsChanged
event.
OnMaximumSizeChanged Raises the MaximumSizeChanged event.
OnMouseDown (inherited from Control) Raises the MouseDown event.
OnMouseEnter (inherited from Control) Raises the MouseEnter event.
OnMouseHover (inherited from Control) Raises the MouseHover event.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
OnMouseLeave (inherited from Control) Raises the MouseLeave event.
OnMouseMove (inherited from Control) Raises the MouseMove event.
OnMouseUp (inherited from Control) Raises the MouseUp event.
OnMouseWheel (inherited from Control) Raises the MouseWheel event.
OnMove (inherited from Control) Raises the Move event.
OnNotifyMessage (inherited from Control) Notifies the control of Windows messages.
OnPaint Overridden. See Control.OnPaint.
OnValidated (inherited from Control) Raises the Validated event.
OnValidating (inherited from Control) Raises the Validating event.
OnVisibleChanged Overridden. See
Control.OnVisibleChanged.
ProcessCmdKey Overridden. See Control.ProcessCmdKey.
ProcessDialogChar (inherited from Control) Processes a dialog character.
ProcessDialogKey Overridden. See
Control.ProcessDialogKey.
ProcessKeyEventArgs (inherited from Control) Processes a key message and generates the
appropriate control events.
ProcessKeyMessage (inherited from Control) Processes a keyboard message.
ProcessKeyPreview Overridden. See
Control.ProcessKeyPreview.
ProcessTabKey Overridden. See
ContainerControl.ProcessTabKey.
WndProc Overridden. See Control.WndProc.
Ex pt WndProc
Prototip
protected virtual void WndProc(ref Message m );
Parametri
m Mesajul Windows de procesat.
Observatii
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
Toate mesajele sunt trimise catre metoda WndProc dupa ce au fost filtrate de metoda
PreProcessMessage.
[
public virtual bool PreProcessMessage(ref Message msg);
Parameters msg A Message, passed by reference, that represents the message to
process.
Return Value
true if the message was processed by the control; otherwise, false.
Remarks
This method is only called when the control is hosted in a Windows Forms
application or as an ActiveX control.
]
Metoda WndProc corespunde exact functiei Windows WindowProc. Controalele derivate trebuie sa apeleze metoda din clasa de baza daca nu trateaza mesajul.
Ce inseamna WindowProc?
The WindowProc function is an application-defined function that processes messages sent to a window. The
WNDPROC type defines a pointer to this callback function. WindowProc is a placeholder for the application-
defined function name.
Syntax
LRESULT CALLBACK WindowProc (
HWND hwnd,
UINT uMsg, WPARAM wParam,
LPARAM lParam
); Parameters
hwnd
[in] Handle to the window.
uMsg
[in] Specifies the message.
wParam
[in] Specifies additional message information. The contents of this
parameter depend on the value of the uMsg parameter.
lParam
[in] Specifies additional message information. The contents of this
parameter depend on the value of the uMsg parameter.
Return Value
The return value is the result of the message processing and depends on the message sent.
Ex in C# pentru WndProc
using System;
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
using System.Drawing; using System.Windows.Forms; namespace c13 { public class Form1 : System.Windows.Forms.Form { // Constant value was found in the "windows.h" header file.
private const int WM_ACTIVATEAPP = 0x001C; private bool appActive = true; [STAThread] static void Main() { Application.Run(new Form1()); } public Form1() { this.Size = new System.Drawing.Size(300,300); this.Text = "Form1"; this.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); } protected override void OnPaint(PaintEventArgs e) { // Paint a string in different styles depending on whether the // application is active.
if (appActive) { e.Graphics.FillRectangle(SystemBrushes.ActiveCaption,20,20,260,50); e.Graphics.DrawString("Application is active", this.Font, SystemBrushes.ActiveCaptionText, 20,20); } else { e.Graphics.FillRectangle(SystemBrushes.InactiveCaption,20,20,260,50); e.Graphics.DrawString("Application is Inactive", this.Font, SystemBrushes.ActiveCaptionText, 20,20); } } [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
protected override void WndProc(ref Message m) { // Listen for operating system messages. switch (m.Msg) { // The WM_ACTIVATEAPP message occurs when the application // becomes the active application or becomes inactive.
case WM_ACTIVATEAPP: // The WParam value identifies what is occurring.
appActive = (((int)m.WParam != 0)); // Invalidate to get new text painted. this.Invalidate(); break; } base.WndProc(ref m); } } }
Un exemplu de folosire a catorva proprietati:
using System.Drawing; using System.Windows.Drawing; class FormProperties { public static void Main()
{ Form form = new Form(); form.Text = Form properties; form.BackColor = Color.Blue; form.Width *= 2; form.Height /= 2; form.FormBorderStyle = FormBorderStyle.FixedSingle;
form.MinimizeBox = true; form.MaximizeBox = true;
form.Cursor = Cursors.Hand; // Application.Run(form); }
}
Keyboard in .NET
Gestionarea intrarilor (modelul event-driven)
Fiecarui tip de intrare (mouse, tastatura, meniu, etc.) ii este asociata o metoda dintr-o anumita
clasa. Cand se produce un eveniment se apeleaza metoda corecta, iar aceasta metoda nu este
intrerupta de nici o alta metoda chiar daca intre timp s-au produs si alte eveniment si deci e
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
nevoie de executia altor metode. Toate aceste metode sunt executate in acelasi fir si se executa in
mod secvential (cu mici exceptii).
Cand un program defineste o metoda ce va trata un eveniment, metoda se numeste event handler
care lucreaza impreuna cu un delegate (defineste prototipul functiei).
Navigarea intre controalele continute intr-o fereastra (form) se face cu TAB si Shift +Tab.
Focus
Primul concept legat de keyboard este focus-ul. La un moment dat numai o fereastra are focus-ul
sau keyboard focus. Aceasta fereastra va primi mesajele de la tastatura pina cand focusul se
schimba. Aceasta este o trasatura fundamentala a Windows-ului, nu a .Net-ului.
In .NET, o fereastra ce poate avea focusul trebuie sa fie reprezentat de o clasa .NET derivata din
Control (Form este derivata din Control).
Pentru ca un control sa aiba focusul, trebuiesc indeplinite urmatoarele conditii:
1. Proprietatile Visible si Enabled trebuie sa fie true. 2. Trebuie sa fie continut in alt control.
3. Toate controalele parinte ale acestor controale trebuie sa fie Visible si Enabled.
4. Proprietatea ControlStyles.Selectable trebuie sa fie true.
Observatie: Urmatoarele controale nu sunt selectabile: Panel, GroupBox,
Splitter, Label, ProgressBar, PictureBox si LinkLabel cand nu contine un link.
Fereastra top (derivata din Form) nu trebuie sa fie continuta in alt control.
Documentatia Microsoft spune ca aceasta fereastra primeste focusul si raspunde la keyboards
events daca si numai daca nu contine alte controale.
Tastele apasate si caracterele (Key Presses and Characters)
Cand se apasa o tasta se emit doua tipuri de semnale ce contin:
1. bytes care identifica tasata apasata
2. bytes ce specifica codul caracterului.
Tastele pot fi grupate astfel:
taste caracter: acestea produc un cod al caracterului si un cod de identificare al tastei.
Taste toggle: NumLock, CapsLock, ScrollLock si uneori Ins, taste ce schimba starea altor
taste.
Taste Shift, Ctrl, Alt ce se folosesc in combinatie cu alte taste.
Taste non-caracter: F1, F2, sageti, ..., acestea produc numai un byte de identificare al tastei (nu
exista cod caracter).
Aceste informatii sunt trimise la calculator cand:
tasta este eliberata
tasta este apasata
tasta este in starea autorepeat (tinuta apasata mai mult timp).
Legatura dintre keyboard si Windows
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
BIOS-ul primeste bytes pentru eveniment de la tastatura si genereaza o intrerupere keyboard.
Codul ce se executa apartine sistemului de operare Windows (cand este instalat acest SO) si SO
Windows construieste anumite mesaje pe care le plaseaza in coada de mesaje a ferestrei ce are
focusul.
Evenimentele KeyDown si KeyUp
Functiile ce trateaza aceste evenimente au un argument din care extrag codul tastei, adica
identifica ce tasta a fost apasata. De asemenea exista o proprietate Keys ale carei valori identifica tasta: Keys.A, Keys.B, etc.
Event Method Delegate Argument
KeyDown OnKeyDown KeyEventHandler KeyEventArgs
KeyUp OnKeyUp KeyEventHandler KeyEventArgs
Putem suprascrie aceste metode:
protected override void OnKeyDown(KeyEventArgs kea) { } protected override void OnKeyUp(KeyEventArgs kea) { }
KeyEventArgs are urmatoarele proprietati:
Cele mai folosite proprietati sunt KeyData si Handled.
Daca Handled este setat pe true aceasta inseamna ca mesajul a fost tratat si nu este trimis mai departe.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
CapsLock si NumLock
Aceste taste au o stare ce poate on sau off. In momentul de fata nu exista o cale de a determina
(din .NET) starea acestor taste (vezi Ch. Petzold). Problema poate fi rezolvata folosind apeluri de
functii Win32 API.
In mod normal ar trebui sa cream o clasa ce contine functiile apelate din Win32 API.
using System; using System.Runtime.InteropServices; public class Win32 { public Win32() {} [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true, CallingConvention=CallingConvention.Winapi)] public static extern short GetKeyState(int keyCode); public bool GetCapsLock() { bool CapsLock = (((ushort) GetKeyState(0x14)) & 0xffff) != 0; /* 0x14 este VK_CAPITAL in Win32 */ /* Trebuiesc consultate fisierele header din Win32 */ return CapsLock; } public bool GetNumLock() { bool NumLock = (((ushort) GetKeyState(0x90)) & 0xffff) != 0; /* 0x90 is VK_NUMLOCK */ return NumLock; } }
Observatie: In exemplu practic GetCapsLock si GetNumLock sunt statice.
Implicit tastele sageti sunt filtrate. Daca dorim ca un control sa manipuleze aceste evenimente,
trebuie sa suprascriem metoda IsInputKey ca in exemplul de mai jos.
using System.Windows.Forms; protected override bool IsInputKey( Keys keyData ) { switch ( keyData ) { case Keys.Up: case Keys.Down: case Keys.Left: case Keys.Right:
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
return true; } return base.IsInputKey( keyData ); }
In continuare putem procesa aceste taste suprascriind metoda OnKeyDown din control.
Daca dorim ca controlul nostru sa trateze toate tastele atunci putem scrie:
protected override bool IsInputKey( Keys keyData ) { return true; }
Pentru a trata evenimentele de la tastaura la nivelul ferestrei (form) si a nu permite altor
controale sa primeasca aceste evenimente, documentatia Microsoft spune ca proprietatea
KeyPressEventArgs.Handled = true in metoda ce trateaza evenimentul KeyPress al formei (ferestrei).
Input focus
Input focus determina ce control primeste intrarile de la tastatura.
Form mosteneste trei proprietati read-only despre focus.
Un control nu poate avea focusul daca este invizibil sau disable.
Proprietatea ContainsFocus returneaza true daca form-ul sau un control din form are focusul.
Proprietatea Focused returneaza true daca controlul are focusul.
Metoda Focus() muta focusul pe un anumit control; daca valoarea returnata este true atunci s-a mutat focusul pe control.
Exista doua evenimente ce spun daca un control a primit sau pierdut focusul.
Mouse
Sunt implicate patru evenimente principale.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
Clasa MouseEventArgs are cinci proprietati:
Button este o valoare din enumerarea MouseButtons
Pentru evenimentele MouseUp, MouseDown, proprietatea Button semnifica ce buton al mouse-
ului a fost apasat sau eliberat. Pentru ev. MouseMove, prop. Button specifica ce buton al mouse-
ului este apasat in timpul miscarii.
Clic si dublu clic
Evenimentele sunt
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
Secventa de mesje pentru dublu clic este:
Clasa Control suporta doua proprietati statice ce ne dau informatii despre pozitia mouse-ului:
Putem folosi aceste proprietati in momentul cand tratam un eveniment.
Diverse probleme
Cum se determina daca tastele Alt, Shift sau Ctrl sunt apasate fara a trata evenimentul?
Se foloseste proprietatea statica Control.ModifierKeys.
Console.WriteLine(Control.ModifierKeys);
if ( (Control.ModifierKeys & Keys.Shift) != 0 )
Console.WriteLine("the shift key is down");
if ( (Control.ModifierKeys & Keys.Alt) != 0 )
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
Console.WriteLine("the alt key is down");
if ( (Control.ModifierKeys & Keys.Control) != 0 )
Console.WriteLine("the control key is down");
Tratarea evenimentului Paint
Paint este un eveniment definit in clasa Control.
Ne vom indrepta atentia asupra functiei PaintEventHandler (definita in System.Windows.Forms) ce are prototipul:
public delegate void PaintEventHandler(object objSender, PaintEventArgs pea);
sender Sursa evenimentului.
pea Un PaintEventArgs ce contine datele evenimentului. Un PaintEventArgs specifica
obiectul Graphics ce poate fi folosit pentru a desena controlul si ClipRectangle in care se va
desena. Desenarea se face intotdeauna cu ajutorul unui context de dispozitiv.
Proprietatea Graphics contine o instanta a clasei Graphics, care este definita in spatiul de
nume System.Drawing. Spatiul de nume Graphics implementeaza un sistem de programare gafic cunoscut sub numele de GDI+ care este o versiune imbunatatita a GDI din Windows.
Exemplu de cod ce implementeaza un handler pentru Paint.
using System; using System.Drawing; using System.Windows.Forms; class PaintEvent {
public static void Main() {
Form f = new Form(); f.Text = Paint event; f.Paint += new PaintEventHandler(MyPaintHandler); Application.Run(f);
} static void MyPaintHandler(object sender, PaintEventArgs pea) {
Graphics g = pea.Grafphics; g.Clear(Color.Red);
} }
O aplicatie Windows normala ar trebui sa contina (minim) urmatoarele spatii de nume: using System;
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
using System.Drawing; using System.Windows.Forms;
Clasa Graphics
Graphics Members
Public Properties
Clip Gets or sets a Region object that limits the
drawing region of this Graphics object.
DpiX Gets the horizontal resolution of this Graphics
object.
DpiY Gets the vertical resolution of this Graphics
object.
TextContrast Gets or sets the gamma correction value for
rendering text.
TextRenderingHint Gets or sets the rendering mode for text
associated with this Graphics object.
Transform Gets or sets the world transformation for this
Graphics object.
VisibleClipBounds Gets or sets the bounding rectangle of the
visible clipping region of this Graphics object.
Public Methods
Clear Clears the entire drawing surface and fills it
with the specified background color.
CreateObjRef (inherited from
MarshalByRefObject)
Creates an object that contains all the relevant
information required to generate a proxy used to
communicate with a remote object.
Dispose Releases all resources used by this Graphics
object.
DrawArc Overloaded. Draws an arc representing a
portion of an ellipse specified by a pair of
coordinates, a width, and a height.
DrawBezier Overloaded. Draws a Bzier spline defined by
four Point structures.
DrawBeziers Overloaded. Draws a series of Bzier splines
from an array of Point structures.
DrawClosedCurve Overloaded. Draws a closed cardinal spline
defined by an array of Point structures.
DrawCurve Overloaded. Draws a cardinal spline through a
specified array of Point structures.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
DrawEllipse Overloaded. Draws an ellipse defined by a
bounding rectangle specified by a pair of
coordinates, a height, and a width.
DrawIcon Overloaded. Draws the image represented by
the specified Icon object at the specified
coordinates.
DrawIconUnstretched Draws the image represented by the specified
Icon object without scaling the image.
DrawImage Overloaded. Draws the specified Image object
at the specified location and with the original
size.
DrawImageUnscaled Overloaded. Draws the specified image using
its original physical size at the location
specified by a coordinate pair.
DrawLine Overloaded. Draws a line connecting the two
points specified by coordinate pairs.
DrawLines Overloaded. Draws a series of line segments
that connect an array of Point structures.
DrawPath Draws a GraphicsPath object.
DrawPie Overloaded. Draws a pie shape defined by an
ellipse specified by a coordinate pair, a width,
and a height and two radial lines.
DrawPolygon Overloaded. Draws a polygon defined by an
array of Point structures.
DrawRectangle Overloaded. Draws a rectangle specified by a
coordinate pair, a width, and a height.
DrawRectangles Overloaded. Draws a series of rectangles
specified by Rectangle structures.
DrawString Overloaded. Draws the specified text string at
the specified location with the specified Brush
and Font objects.
ExcludeClip Overloaded. Updates the clip region of this
Graphics object to exclude the area specified
by a Rectangle structure.
FillClosedCurve Overloaded. Fills the interior a closed cardinal
spline curve defined by an array of Point
structures.
FillEllipse Overloaded. Fills the interior of an ellipse
defined by a bounding rectangle specified by a
pair of coordinates, a width, and a height.
FillPath Fills the interior of a GraphicsPath object.
FillPie Overloaded. Fills the interior of a pie section
defined by an ellipse specified by a pair of
coordinates, a width, and a height and two
radial lines.
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
FillPolygon Overloaded. Fills the interior of a polygon
defined by an array of points specified by Point
structures.
FillRectangle Overloaded. Fills the interior of a rectangle
specified by a pair of coordinates, a width, and
a height.
FillRectangles Overloaded. Fills the interiors of a series of
rectangles specified by Rectangle structures.
FillRegion Fills the interior of a Region object.
Flush Overloaded. Forces execution of all pending
graphics operations and returns immediately
without waiting for the operations to finish.
GetHdc Gets the handle to the device context associated
with this Graphics object.
IsVisible Overloaded. Indicates whether the point
specified by a pair of coordinates is contained
within the visible clip region of this Graphics
object.
MeasureCharacterRanges Gets an array of Region objects, each of which
bounds a range of character positions within the
specified string.
MeasureString Overloaded. Measures the specified string when
drawn with the specified Font object.
MultiplyTransform Overloaded. Multiplies the world
transformation of this Graphics object and
specified the Matrix object.
ReleaseHdc Releases a device context handle obtained by a
previous call to the GetHdc method of this
Graphics object.
ReleaseHdcInternal Internal method. Do not use.
ResetClip Resets the clip region of this Graphics object to
an infinite region.
ResetTransform Resets the world transformation matrix of this
Graphics object to the identity matrix.
Restore Restores the state of this Graphics object to the
state represented by a GraphicsState object.
RotateTransform Overloaded. Applies the specified rotation to
the transformation matrix of this Graphics
object.
Save Saves the current state of this Graphics object
and identifies the saved state with a
GraphicsState object.
ScaleTransform Overloaded. Applies the specified scaling
operation to the transformation matrix of this
Graphics object by prepending it to the object's
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
transformation matrix.
SetClip Overloaded. Sets the clipping region of this
Graphics object to the Clip property of the
specified Graphics object.
ToString (inherited from Object) Returns a String that represents the current
Object.
TransformPoints Overloaded. Transforms an array of points from
one coordinate space to another using the
current world and page transformations of this
Graphics object.
TranslateClip Overloaded. Translates the clipping region of
this Graphics object by specified amounts in
the horizontal and vertical directions.
TranslateTransform Overloaded. Prepends the specified translation
to the transformation matrix of this Graphics
object.
Metoda OnPaint ( si celelalte metode On)
-
Introducere in Windows Forms
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi 21.01.2007
Ioan Asiminoaei
iar rezultatul este:
Evenimentele si metodele On
Putem crea o instanta a clasei Control sau a unei clase derivate din Control, putem instala un event handler pentru Paint definind o metoda statica cu aceeasi parametri (tip si ordine) si
acceasi valoare de retur (acelasi tip) ca mai sus si apoi atasam evenimentului Paint metoda
definita sau putem suprascrie (intr-o clasa derivata din Control) metoda OnPaint.
Toate evenimentele definite in Windows Forms sunt similare. Fiecarui eveniment ii corespunde
o metoda protected. Pentru fiecare eveniment vom intilni ceva de genul urmator:
Observatie: In toate metodele override pentru On se va apela metoda On din clasa de baza:
base.On();