custom components –and- custom controls for the.net compact framework paul yao the paul yao...
TRANSCRIPT
Custom Components Custom Components ––and-and- Custom Controls Custom Controls for the for the .NET Compact .NET Compact FrameworkFramework
Paul YaoPaul YaoThe Paul Yao CompanyThe Paul Yao Companyhttp://www.paulyao.comhttp://www.paulyao.com
DisplayDisplayUSB or SerialUSB or Serial
ProcessorProcessorMemoryMemory
GSM/GPRSGSM/GPRSCDMA/1xRTTCDMA/1xRTT
Device Device HardwareHardware
WiFiWiFiBluetoothBluetooth
RadioRadio
DriversDrivers
Windows MobileWindows Mobile CE DBCE DBActiveSyncActiveSync
Pocket OutlookPocket OutlookPocket Internet ExplorerPocket Internet ExplorerWindows Media PlayerWindows Media Player
Windows CEWindows CE
Software Platform (APIs)Software Platform (APIs)
Home ScreenHome ScreenUser Interface/ShellUser Interface/ShellHTML ControlHTML Control
GAPIGAPIRemote APIRemote APIConfigurationConfigurationBluetoothBluetoothSecuritySecurity
Connection ManagerConnection Manager TAPITAPISMS SMS MAPI MAPI POOM POOM ActiveSyncActiveSync
MultimediaMultimediaCommunicatioCommunicationn
Device ManagementDevice Management PresentationPresentation
ADO CEADO CEXMLXMLCE DBCE DBOLE DBOLE DB
Data AccessData Access
NativeNative
Win32Win32
MFCMFC ATLATL
ManagedManaged
.NET Compact.NET CompactFrameworkFramework
Server sideServer side
ASP .NETASP .NETMobile ControlsMobile Controls
NativeNative
Win32Win32
MFCMFC ATLATL
ManagedManaged
.NET Compact.NET CompactFrameworkFramework
Server sideServer side
ASP .NETASP .NETMobile ControlsMobile Controls
Windows Mobile Development PlatformWindows Mobile Development Platform:: TodayToday
Embedded VC++Embedded VC++ Visual Studio .NETVisual Studio .NET
AgendaAgenda
Part 1: Control FundamentalsPart 1: Control Fundamentals
Part 2: Creating Custom ControlsPart 2: Creating Custom Controls
Part 3: Designer SupportPart 3: Designer Support
Downloads:Downloads:PPT: http://www.paulyao.com/msmdc_cli355.pptPPT: http://www.paulyao.com/msmdc_cli355.pptSample: Sample: http://www.paulyao.com/postalcodecontrol.ziphttp://www.paulyao.com/postalcodecontrol.zip
Part 1: Control Part 1: Control FundamentalsFundamentals
TerminologyTerminologySupported ControlsSupported ControlsUnsupported ControlsUnsupported ControlsSupport for InheritedSupport for Inherited
PropertiesPropertiesMethodsMethodsEventsEventsa.k.a. “PME’s”a.k.a. “PME’s”
Terminology (1/3)Terminology (1/3)Control vs. ComponentControl vs. Component
A Control A Control Derives from Derives from ControlControl class classWraps around a Windows API windowWraps around a Windows API windowNormally is visibleNormally is visible
A ComponentA ComponentDerives from Derives from ComponentComponent class classDoes not wrap around a Windows API Does not wrap around a Windows API windowwindowCan be visible (Can be visible (ToolbarToolbar, , MenuItemMenuItem))Can be invisible (Can be invisible (TimerTimer))
In common parlance, “custom In common parlance, “custom control” includes both controls and control” includes both controls and components.components.
Terminology (2/3)Terminology (2/3)PMEs = Properties, Methods, & PMEs = Properties, Methods, & EventsEventsProperties – public data members; Properties – public data members;
can be read-only, write-only, or can be read-only, write-only, or read/write (are really fields hidden in read/write (are really fields hidden in a method)a method)Methods – class functions. Can be Methods – class functions. Can be static (per-class) or instanced (per-static (per-class) or instanced (per-object).object).Events – Outward-bound method Events – Outward-bound method calls that let the outside world know calls that let the outside world know of a change to the inner state of an of a change to the inner state of an object.object.
Terminology (3/3)Terminology (3/3)Inherited and SupportedInherited and Supported
InheritedInheritedA derived class A derived class inheritsinherits all PMEs from all PMEs from base classesbase classesExample: Example: LabelLabel inherits all PMEs from inherits all PMEs from ControlControl
SupportedSupportedProperty – control uses propertyProperty – control uses propertyMethod – method is implementedMethod – method is implementedEvent – control calls event handler Event – control calls event handler methods when the event occursmethods when the event occurs
““Inherited does not Inherited does not mean supportedmean supported””
––Seth Demsey, Seth Demsey, .NET Compact Framework .NET Compact Framework Team, Team, Microsoft CorporationMicrosoft Corporation
Controls IncludedControls IncludedIn the .NET Compact FrameworkIn the .NET Compact Framework
ButtonButtonCheckBoxCheckBoxComboBoxComboBoxContextMenuContextMenuDataGridDataGridDomainUpDownDomainUpDownImageListImageListLabel Label ListBoxListBoxMainMenuMainMenuMenuItemMenuItemNumericUpDownNumericUpDownPanelPanelPictureBoxPictureBox
ProgressBarProgressBarRadioButtonRadioButtonHScrollBarHScrollBarVScrollBarVScrollBarStatusBarStatusBarTabControlTabControlTabPageTabPageTextBoxTextBoxTimerTimerToolBarToolBarToolBarButtonToolBarButtonTrackBarTrackBarListViewListViewTreeViewTreeView
Controls ExcludedControls ExcludedFrom .NET Framework controlsFrom .NET Framework controls
CheckedListBoxCheckedListBoxDateTimePickerDateTimePickerErrorProviderErrorProviderGroupBoxGroupBoxHelpProviderHelpProviderLinkLabelLinkLabelMdiClientMdiClientMonthCalendarMonthCalendarNotifyIconNotifyIconPrintPreviewControlPrintPreviewControlRichTextBoxRichTextBoxSplitterSplitterTooltipTooltip
Control PMEsControl PMEsSupported PropertiesSupported Properties
““Inherited does not mean supported”Inherited does not mean supported”
ObjectObject
MarshallByRefObjectMarshallByRefObject
ComponentComponent
ControlControl
LabelLabel
Supports 27 of Supports 27 of 76 properties 76 properties
of desktop of desktop counterpartcounterpart
Label Supports 20 Label Supports 20 of 27 propertiesof 27 properties
Control PMEsControl PMEsSupported PropertiesSupported Properties
Other Label Other Label PropertiesProperties
BindingContextBindingContextBottom, Left, Top, Bottom, Left, Top, RightRightBoundsBoundsClientRectangleClientRectangleClientSizeClientSizeDataBindingsDataBindingsHeight, WidthHeight, WidthTopLevelControlTopLevelControl
Control PMEsControl PMEsSupported MethodsSupported Methods
““Inherited does not mean supported”Inherited does not mean supported”
Supports 30 of Supports 30 of 161 methods 161 methods of desktop of desktop counterpartcounterpart
Label supports 15 Label supports 15 of 30 methodsof 30 methods
ObjectObject
MarshallByRefObjectMarshallByRefObject
ComponentComponent
ControlControl
LabelLabel
Control PMEsControl PMEsSupported MethodsSupported Methods
Docs Docs show show methods methods supportesupported in CF d in CF controls controls
Control PMEsControl PMEsSupported EventsSupported Events
““Inherited does not mean supported”Inherited does not mean supported”
Supports 17 of Supports 17 of 58 events of 58 events of
desktop desktop counterpartcounterpart
Label supports 5 Label supports 5 of 17 eventsof 17 events
ObjectObject
MarshallByRefObjectMarshallByRefObject
ComponentComponent
ControlControl
LabelLabel
Control PMEsControl PMEsSupported EventsSupported Events
CF Label Events:CF Label Events:DisposedDisposedParentChangedParentChangedTextChangedTextChangedValidatedValidatedValidatingValidating
Control PMEsControl PMEsSupported EventsSupported EventsThe “Magnificent Seven”The “Magnificent Seven”
DisposedDisposedParentChangedParentChangedValidatedValidatedValidatingValidatingEnabledChangedEnabledChangedGotFocusGotFocusLostFocusLostFocus
Three new events…Three new events…KeyDownKeyDownKeyPressKeyPressKeyUpKeyUp
Supported by Supported by allall controlscontrols
Partially SupportedPartially SupportedClickClickTextChangedTextChangedKeyDownKeyDownKeyPressKeyPressKeyUpKeyUpMouseDownMouseDownMouseMoveMouseMoveMouseUpMouseUp
TenTen
requirrequir
es es
sp2sp2
Part 2: Creating Custom Part 2: Creating Custom ControlsControls
Design IssuesDesign IssuesDemo: PostalCode custom controlDemo: PostalCode custom controlDefining & Refining:Defining & Refining:
PropertiesPropertiesMethodsMethodsEventsEvents
Building Custom ControlsBuilding Custom Controls
Design IssuesDesign IssuesRationale for Custom ControlsRationale for Custom Controls
Refine behavior of existing controlsRefine behavior of existing controlsEx: Number-only text boxEx: Number-only text box
Create new type of controlCreate new type of controlEx: Network status displayEx: Network status display
Wrap library services for third-party Wrap library services for third-party developersdevelopers
Bar-code scanner controlBar-code scanner controlPrinter outputPrinter output
Design IssuesDesign IssuesAlternative Types of Custom Alternative Types of Custom ControlsControls1.1. Derive from an existing control.Derive from an existing control.
Existing control closely matches requirementsExisting control closely matches requirementsOnly fine-tuning is neededOnly fine-tuning is neededExample: Example: TextBoxTextBox for date-only input for date-only input
2.2. Create composite controlsCreate composite controlsGroup existing controls to operate as a unitGroup existing controls to operate as a unitKey benefit: reusabilityKey benefit: reusabilityExample: Customer contact fieldsExample: Customer contact fields
3.3. Create new controlsCreate new controlsExisting controls do not match requirementsExisting controls do not match requirementsWant to create unique look and feelWant to create unique look and feelExample: Bar-code reader controlExample: Bar-code reader control
Design IssuesDesign IssuesPackaging AlternativesPackaging Alternatives
In your program’s executable (.exe) In your program’s executable (.exe) filefile
Add to Visual Studio .NET projectAdd to Visual Studio .NET projectBind to your programBind to your program
In a separate class library (.dll) fileIn a separate class library (.dll) fileCan be shipped, shared, installed, Can be shipped, shared, installed, updatedupdatedCan install to the Global Assembly Can install to the Global Assembly Cache (GAC)Cache (GAC)
Key Benefit: save mobile device storage Key Benefit: save mobile device storage space.space.Note: no performance benefits (no pre-JIT)Note: no performance benefits (no pre-JIT)
Design IssuesDesign IssuesThree choices for a base classThree choices for a base class
Existing control class:Existing control class:TextBoxTextBox, , ListBoxListBox, etc., etc.
System.Windows.Forms.ControlSystem.Windows.Forms.Control Wrapper for an OS windowWrapper for an OS windowCan be visible or invisibleCan be visible or invisibleIn Designer, is placed on Form / PanelIn Designer, is placed on Form / Panel
System.ComponentModel.ComponentSystem.ComponentModel.Component Wrapper for everything elseWrapper for everything elseCan be visible or invibleCan be visible or invibleIn Designer, is placed In Designer, is placed
Design IssuesDesign IssuesSupport for Paint eventSupport for Paint event
Only In These Control ClassesOnly In These Control ClassesFormFormControlControlPanelPanelPictureBoxPictureBoxDataGridDataGrid
Design IssuesDesign IssuesSupport for input eventsSupport for input events
Keyboard Events – support in all Keyboard Events – support in all ControlControl-derived classes (requires -derived classes (requires CF/ SP2)CF/ SP2)Mouse Events – Mouse Events – MouseDown/Move/UpMouseDown/Move/Up
Support in: Support in: ControlControl, , DataGridDataGrid, , FormForm, , PanelPanel, , PictureBoxPictureBox, , TabPageTabPage
No support in other control classesNo support in other control classes
Click EventClick EventSupport in: Support in: ButtonButton, , CheckBoxCheckBox, , ControlControl, , DataGridDataGrid, , FormForm, , MenuItemMenuItem, , PanelPanel, , PictureBoxPictureBox, , RadioButtonRadioButton, , TabPageTabPage
No support in other control classesNo support in other control classes
Postal CodePostal CodeCustom ControlCustom Control
1.1. Modify existing MyAddress Modify existing MyAddress program.program.
2.2. Create custom control for Create custom control for validating postal codes from validating postal codes from three countries (Canada, three countries (Canada, Mexico, Singapore)Mexico, Singapore)
Postal Code Custom Postal Code Custom ControlControlElementsElementsPropertiesProperties
bool bool AllowSpaceAllowSpace – space character – space characterbool bool AllowLettersAllowLetters – alphabetic letters – alphabetic letters
MethodsMethodsOverride base class Override base class OnKeyPressOnKeyPress
EventsEventsTextChangedTextChanged – register to receive from – register to receive from base classbase classPostalCodeChangedPostalCodeChanged – new event – new event
Building Custom ControlsBuilding Custom ControlsDefining a propertyDefining a property
Private fields for public propertiesPrivate fields for public propertiesprivate bool m_bAllowSpace = false;private bool m_bAllowSpace = false;
Property definition:Property definition:public bool AllowSpacepublic bool AllowSpace
{{
get { return m_bAllowSpace; }get { return m_bAllowSpace; }
set { m_bAllowSpace = value; }set { m_bAllowSpace = value; }
} // property: AllowSpace} // property: AllowSpace
Building Custom ControlsBuilding Custom ControlsOverriding existing methodsOverriding existing methods
Method original definitionMethod original definitionprotected virtual protected virtual
void OnKeyPress(void OnKeyPress(KeyPressEventArgs e);KeyPressEventArgs e);
Declaration for method override:Declaration for method override:protected override protected override
void OnKeyPress(void OnKeyPress(KeyPressEventArgs e)KeyPressEventArgs e)
Building Custom ControlsBuilding Custom ControlsCreating events (1/3)Creating events (1/3)1.1. Field for delegate collectionField for delegate collection
private EventHandler m_evPostalCodeChanged;private EventHandler m_evPostalCodeChanged;
2.2. Event for adding/removing delegatesEvent for adding/removing delegatespublic event EventHandlerpublic event EventHandler
PostalCodeChanged PostalCodeChanged
{{
add { m_evPostalCodeChanged += value; }add { m_evPostalCodeChanged += value; }
remove { m_evPostalCodeChanged -= value;}remove { m_evPostalCodeChanged -= value;}
}}
Building Custom ControlsBuilding Custom ControlsCreating events (2/3)Creating events (2/3)3.3. Method as event broadcaster (‘Method as event broadcaster (‘OnOn’ ’
prefix)prefix)protected virtual void protected virtual void
OnPostalCodeChanged(EventArgs e) OnPostalCodeChanged(EventArgs e)
{{
if (m_evPostalCodeChanged != null) if (m_evPostalCodeChanged != null)
{{
m_evPostalCodeChanged.Invoke(m_evPostalCodeChanged.Invoke(
this, e);this, e);
}}
}}
Building Custom ControlsBuilding Custom ControlsCreating events (3/3)Creating events (3/3)4.4. Code to call event broadcaster:Code to call event broadcaster:
private void private void
PostalCodeTextBox_TextChanged(PostalCodeTextBox_TextChanged(
object sender, EventArgs e)object sender, EventArgs e)
{{
if (Text.Length == MaxLength)if (Text.Length == MaxLength)
{{
OnPostalCodeChanged(EventArgs.Empty);OnPostalCodeChanged(EventArgs.Empty);
}}
}}
Part 3: Designer SupportPart 3: Designer Support
The GoalThe GoalThe ChallengesThe ChallengesSetting Up Visual Studio .NETSetting Up Visual Studio .NETDesigner DLLDesigner DLLFine-Tuning with AttributesFine-Tuning with Attributes
The GoalThe Goal
Add control to Add control to Designer ToolboxDesigner ToolboxEnableEnable
Drag & DropDrag & DropEdit propertiesEdit propertiesAdd event Add event handlershandlers
The ChallengesThe Challenges
WhatWhatNeed two Need two DLLsDLLs
Might have Might have redundant redundant source codesource code
Requires C#Requires C#
WhyWhyVS.NET uses .NET VS.NET uses .NET Framework; devices Framework; devices use .NET Compact use .NET Compact FrameworkFrameworkVS .NET does not like to VS .NET does not like to share source files share source files between projects; need between projects; need to play tricks to ‘tame’ to play tricks to ‘tame’ VS .NETVS .NET
VB.NET does not VB.NET does not tolerate duplicate, tolerate duplicate, ambiguous namesambiguous names
Setting Up Visual Setting Up Visual Studio .NETStudio .NETFor a custom control libraryFor a custom control libraryGoal: Three projects in one directoryGoal: Three projects in one directory
App – Smart Device App, for testingApp – Smart Device App, for testingDeviceLib – Smart Device class libraryDeviceLib – Smart Device class libraryDesignLib – Desktop designer libraryDesignLib – Desktop designer library
For each:For each:Create projectCreate projectRename AssemblyInfo.cs (example: Rename AssemblyInfo.cs (example: App_AssemblyInfo.cs)App_AssemblyInfo.cs)Close projectClose project
Copy files to common directory, then Copy files to common directory, then Project->Add Existing Item…Project->Add Existing Item…
Setting Device Library Setting Device Library VersionVersionPut that version num in design Put that version num in design librarylibrary
Modify DeviceLib_AssemblyInfo.cs:Modify DeviceLib_AssemblyInfo.cs:Change “1.0.*” to 1.0.<num>.<num>Change “1.0.*” to 1.0.<num>.<num>[assembly: AssemblyVersion("1.0.1.0")][assembly: AssemblyVersion("1.0.1.0")]
Add to DesignLib_AssemblyInfo.cs:Add to DesignLib_AssemblyInfo.cs:[assembly: [assembly:
System.CF.Design.RuntimeAssembly(System.CF.Design.RuntimeAssembly(“DeviceLib, “DeviceLib, Version=1.0.1.0, Version=1.0.1.0, Culture=neutral, Culture=neutral, PublicKeyToken=null")]PublicKeyToken=null")]Optional – match version Optional – match version
[assembly: AssemblyVersion("1.0.1.0")][assembly: AssemblyVersion("1.0.1.0")]
Design LibraryDesign LibraryAssembly ReferencesAssembly References
.NET Framework Assembly:.NET Framework Assembly:System.Windows.Forms.dllSystem.Windows.Forms.dll
Designer Helpers:Designer Helpers:System.CF.Windows.Forms.dllSystem.CF.Windows.Forms.dllSystem.CF.Drawing.dllSystem.CF.Drawing.dll
Tip:Tip:When building, watch for warning for When building, watch for warning for duplicate symbols. Must use CF library.duplicate symbols. Must use CF library.If warning message does If warning message does notnot mention mention CF lib:CF lib:1.1. Delete reference to Delete reference to
System.Windows.Forms.dllSystem.Windows.Forms.dll2.2. Then add it back in (force it to end of search Then add it back in (force it to end of search
list)list)
Installing Two Control Installing Two Control LibrariesLibraries
Shut down Visual Studio .NETShut down Visual Studio .NETCopy files to:Copy files to: \Program Files\Microsoft VS .NET \Program Files\Microsoft VS .NET 2003\2003\
CompactFrameworkSDK\CompactFrameworkSDK\v1.0.5000\v1.0.5000\Windows CE\Windows CE\Designer\Designer\
Start up Visual Studio .NETStart up Visual Studio .NET
Device DLL goes Device DLL goes herehere
Designer DLL Designer DLL goes heregoes here
Modifying ToolboxModifying Toolbox
Summon Context Summon Context MenuMenuSelect Select Add/Remote Add/Remote Items…Items…, then , then select designer select designer librarylibraryCan also do the Can also do the following:following:
Add a new tabAdd a new tabOrganize itemsOrganize items
Adding Design-Time Adding Design-Time Support for the Support for the Postal Code Custom Postal Code Custom ControlControl
1.1. Create .NET Framework Create .NET Framework DLLDLL
2.2. Set version number in Set version number in device-side control librarydevice-side control library
3.3. Set version number in Set version number in designer control librarydesigner control library
After This Session…After This Session…
Visit the Windows Mobile Visit the Windows Mobile booth to:booth to:
Get the Get the Windows Mobile Developer Windows Mobile Developer Resource Kit Resource Kit and start supporting and start supporting landscape and high DPI landscape and high DPI Talk to the Talk to the Technical SupportTechnical Support team teamJoin the Windows Mobile Solutions Join the Windows Mobile Solutions Partner Partner ProgramProgramEnter the Microsoft Enter the Microsoft Mobile2Market Mobile2Market Application ContestApplication Contest
Fill in your evaluation form Fill in your evaluation form sponsored by AT&T Wirelesssponsored by AT&T Wireless
1 MPX200 given away per 1 MPX200 given away per session. See session. See www.mscorpevents.com/mdcwww.mscorpevents.com/mdc
Your Questions…Your Questions…
Thank You!Thank You!
© 2004 Microsoft Corporation. All rights reserved.© 2004 Microsoft Corporation. All rights reserved.MICROSOFT CONFIDENTIAL. INTERNAL USE ONLY.MICROSOFT CONFIDENTIAL. INTERNAL USE ONLY.