Resources

Printing, COM access, Accessibility, Help and Globalisation

Lesson 1 - Print Functionality

The PrintDocument Component

  • Encapsulates all info required to print page
  • PrinterSettings property contains details on available printers capabilities
  • Default PageSettings contains configuration info for a page
  • PrintController describes how each page guided through printing process

Creating PrintDocument object

  • Either via designer or through code
  • Both methods of creation result in component automatically configured to work with default system printer

How Printing Works

  • Printed content provided b y application logic

  • Print job initiated by PrintDocument.Print()

    • Start job
    • Raises 1+ PrintPage event
    • Provide handler for event to print content (if none exists nothing is printed)
  • PrintPage event raised for each page

  • Handler for PrintPage must track print job and ensure correct page printed

PrintPage event

  • Objects and info required to print content wrapped in PrintPageEventArgs object

    • Cancel - indicates if job should be cancelled
    • Graphics - contains Graphics object used to render content
    • HasMorePages - indicates if additional pages should be printed
    • MarginBounds - Rectangle object representing portion of page within margin
    • PageBounds - Rectangle object representing entire page
    • PageSettings - PageSettings object for current page
  • To render content use same methods as to render form

// Method to handle PrintPage event

public void PrintElipse(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawElipse(Pens.Black, e.MarginBounds);
}
  • Specify print job has multiple pages by using HasMorePages property (note, if fail to set to false after last page printed app will continue to raise PrintPage events)
  • Create event handler for PrintPage
    • Double click PrintDocument instance in designer to create default handler
    • Declare event handler in code

Printing Content

  • Use Graphics object supplied by PrintPageEventArgs to render

  • When printing multiple lines of text must include logic to calculate line spacing

    • Calculate number of lines per page by dividing margin bounds height by font height
    • Calculate line position by multiplying font height by line number
  • May use different colours when printing to colour printer as black and white

    • Some colours easily discernible on screen can be indistinguishable on paper
    • Provide alternative logic to accommodate black and white printers
    • Determine printer colour capability using PrinterSettings.SupportsColor
    • Can force printer into black and white mode by setting PrinterSettings.SupportsColor to false

PrintPreviewControl

  • Allows graphical preview of printed content
  • PrintPreviewControl must be associated with PrintDocument instance
myPrintPreview.Document = myPrintDocument;
  • After association made the PrintPreviewControl displays content to be printed by control by capturing output of PrintDocument control
  • Update preview in response to changing conditions by calling InvalidatePreview method
myPrintPreview.InvalidatePreview();
  • The Zoom property specifies magnification level
    • Fractional value reduces image
    • 1 causes preview to be displayed full size
    • Greater than 1 causes an enlargement

PrintPreviewDialog

  • Implements most commonly used print preview functionality
  • Provided as standard by .NET framework
  • Suitable for requirements of most apps - use PrintPreviewControl when require greater control

Printing Configuration

  • Printing support highly configurable
  • PrintDocument.PrinterSettings contains info about available printers, used unless overridden by PrintPage handler
  • When PrintDocument created default config for default printer loaded into PrinterSettings
  • User configuration of print jobs via PrintDialog and PrintSetupDialog

PrintDialog

  • Allow users to set PrinterSettings property of PrintDocument object at runtime
  • Add to app by dragging instance of PrintDialog from WindowsForms tab of Toolbox to designer
  • Display at runtime by calling
PrintDialog1.ShowDialog();
  • Must be associated with PrintDocument object, via PrintDialog.Document property

PrintSetupDialog

  • Used like PrintDialog
  • Allows user to configure page and printer settings at runtime

Configure PageSetting at run time

  • May wish to configure individual pages, e.g. print one in landscape, rest in portrait
  • Change page settings via PrintPageEventArgs.PageSettings - represents settings for page being printed

Lesson 2 - Accessing and Invoking Components

.NET and COM Type Libraries

  • Create reference to type library via Add References dialog

    • .NET tab displays available .NET assemblies
    • COM tab displays COM type libraries
    • Projects tab displays available projects
    • Add reference to unlisted item via Browse button
  • Use the type library

  • Declare and instantiate desired class

  • ActiveX controls = implementation of COM

    • Add reference in same way as other COM objects
    • Can add to Toolbox
    • Have significant performance drawbacks - only use when .NET control equivalent not available

Web Service

  • Web service = class hosted on internet

  • Call its methods either synchronously or asynchronously

  • Create reference in Solution Explorer via Add Web Reference window

    • Navigate to URL of Web reference or
    • Search Online if URL not known
  • Universal Description Discovery Integration (UDDI) allows search of web for components providing web services

    • Company selected web services it offers are displayed
    • Choose service and XML contract shown in left pane
  • When instance created .NET creates proxy representing web service

    • When method called it is relayed to Web service address specified
  • Synchronous calls behave like normal function calls

    • Response times can vary
    • App execution pauses until function returns
  • Asynchronous call to web service invoked on separate thread

    • Permits app execution to continue while call processed
    • For every web service method there are 2 additional asynchronous methods beginning Begin and End
    • Begin async call by calling Begin method passing over synchronous parameters and an AsyncCallback delegate
    • Begin method has return type of IAsyncResult
public class AsyncDemo
{
WebService1 myService;

public void CallMethodAsynchronously()
{
myService = new WebService1();

// Create AsyncCallback delegate
System.AsyncCallback myCallback = new System.AsyncCallback(CallBack);

// Object required by method call but not
// used

myService.BeginMyMethod(myCallback, new Object());
}

public void CallBack(IAsynResult e)
{
string myString;

myString = myService.EndMyMethod(e);
}
}
  • Must specify callback method, but don't need to use it. Can receive data in same method by calling the End method. Program execution will halt at End call until result is available

Accessing Windows API

  • Most important functionality wrapped in .NET classes
  • Use DllImportAttribute to gain access to native functions
[System.Runtime.InteropServices.DllImport("kernel32")]  
private static extern int Beep(int dwFreq, int dwDuration);

Lesson 3 Accessibility

Design

  • Accessibility begins in design

  • Flexibility = key principle

    • User can customise UI to their needs

    • Choose variety of input methods

      • Keyboard access to important tasks
      • Mouse click access for common tasks
    • Choice of output methods

      • Sound
      • Graphics
      • Text
  • Consistent interaction

    • Within itself
    • With other applications
  • Compatibility with accessibility aids

Program Accessibility

Support Standard System Settings

  • Ensures all user apps have consistent look and feel provided by system settings
  • Implement via System objects in .NET framework
  • Design app so can be used on screen at 640 * 480

High Contrast

  • Support high contrast option in system colours
  • Avoid background images (reduces contrast)

Keyboard Access

- Document + make discoverable keyboard access to all app features - Provide shortcut keys to menu items - Set Tab order on dialogs

Notify Keyboard Focus Location

  • Usually managed by .NET framework
  • Always incorporate code to set focus to first control on form when it is first displayed

Do not rely on sound alone

  • Sound is important cue
  • Must also use visual cues
    • flash background colour
    • display message box
    • use non-modal screen to display info while app runs

Accessibility Properties

  • Each control supports 5 properties that determine how it interacts with accessibility aids
    • AccessibleDescription - description reported to accessibility aids
    • AccessibleName - name reported to accessibility aids
    • AccessibleRole - role of control that is reported to accessibility aids. Select value from an enum, normally default unless control behaving peculiarly or is custom then set to value describing it, e.g. set to Chart if control displays a chart
    • AccessibilityObject - read-only instance of AccessibleObject providing info about control to usability aids
    • AccessibleDefaultActionDescription - description of control default action, set in code not via designer

Lesson 4 - Implementing Help

The Help Class

  • Display HTM or CHM files to users
  • Encapsulates HTML Help 1.0 engines
  • Exposes 2 static methods
    • ShowHelp - display help file for particular control. Takes
      • reference to control
      • URL for help file
      • optional navigator specifying help file element to display (TableOfContents, Find, Index, Topic or keyword search)
Help.ShowHelp(MyForm, @"C:\myHelpFile.htm", "HelpMenu");
  • ShowHelpIndex call made same way as for ShowHelp
Help.ShowHelpIndex(MyForm,@"C:\myHelpFile.htm");

HelpProvider Component

  • It is an extender provider - coordinates and maintains properties for each control on form

  • Adds 3 properties to each control on form

    • HelpString - displayed when it has focus and F1 pressed
    • HelpKeyWord
    • HelpNavigator
      • TableOfContents
      • Find
      • Index
      • Topic
      • AssociatedIndex
      • KeywordIndex
  • Can set in properties window during design or in code

  • Can specify HelpNameSpace specifying URL for help file associated with HelpProvider

    • If not set then HelpString displayed and other 2 properties ignored
    • If set displays help file specified by HelpKeyWord and HelpNavigator
      • Can still access HelpString, but only via code using HelpProvider.GetHelpString() method
myHelpProvider.GetHelp(Button1);

Lesson 5 - Globalisation and Localisation

  • Globalisation = apply culture based formatting to data, e.g. use of period as thousand separator and , as decimal

  • Localisation = retrieving appropriate pieces of data based on culture, e.g. different form title based on language (English, French, etc.)

  • Culture = info about region in which app being used. Identified by code.

    • code represents to framework what current language is (2 letter code)

    • can also specify region in which app is used (2 letter code after dash)

    • codes only specifying language = neutral cultures

    • codes specifying region = specific cultures

      • En = English language, no region
      • en-CA = English language, Canada
      • af-ZA = Afrikaans language, South Africa
    • some exceptions

      • Cy-uz-UZ = Uzbek language, Uzbekistan, Cyrillic alphabet
      • Lt-uz-UZ = Uzbek language, Uzbekistan, Latin alphabet
      • zh-CHT = traditional Chinese, no region
      • zh-CHS = simplified Chinese, no region
  • App automatically reads system culture and implements them

  • Change current culture of app by setting CurrentThread.CurrentCulture to new instance of CultureInfo class

System.Threading.Thread.CurrentThread.Currentculture = 

new System.Globalization.CultureInfo("fr-CA");
  • Retrieve CultureInfo for CurrentCulture via CultureInfo.CurrentCulture
CultureInfo myCurrentculture = CultureInfo.CurrentCulture;

Globalisation

  • Data not formatted by application will be unaffected by change to Thread.CurrentThread.CurrentCulture, e.g. label set to "$500" will always display this regardless of culture
Label1.Text = "$500"

Whereas setting to value formatted to currency will result in 500 being displayed for en-GB - note no currency conversion takes place

Label1.Text = (500).ToString("C");

Localisation

  • Localisation supported by creating separate localised form resource files for each culture app supports. At run time appropriate version loaded based on CultureInfo.CurrentUICulture.

  • If resources appropriate to current value of CultureInfo.CurrentUICulture then app displays resources for default culture

  • UI culture must be set before form displaying localised resources is loaded. To set UI culture programmatically should do so in constructor of main form

  • Every form exposes Localizable property indicating if form is localised or not

  • When Localizable property set to true, IDE creates appropriate resource files

    • Based on Language property of form
    • When Language set to Default IDE edits forms and controls for the Default UI culture
    • To create forms for other cultures set Language to appropriate value
  • Localisation not limited to strings, button sizes may change to accommodate longer strings

  • Validating input in international app traditionally difficult, under .NET use validation mechanisms of Char, e.g. Char.IsDigit and Char.IsLetter

Culture-Specific Formatting

  • Can modify specific members of CultureInfo to tailor app functionality - e.g. Japanese bank that deals in $, use Japanese specific formatting, but uses $ as currency symbol
  • Following members define how globalisation formatting carried out
    • DateTimeFormat - how dates and times formatted, e.g. abbreviated day and month names, display of AM and PM, date and time formats, calendar and day names
    • NumberFormat - describes decimal and thousand separators to use for numbers and currency, currency symbol, display of percentages
    • TextInfo - code page to use, list separator
CultureInfo modJPCulture = new CultureInfo("jp-JN");

modJPCulture.NumberFormat.CurrencySymbol = "$";

Thread.CurrentThread.CurrentCulture = modJPCulture;

Right-to-left Display

  • Standard Windows Forms provide RightToLeft property enabling right-to-left UI in app

  • RightToLeft property set to

    • Yes - controls becomes mirror of themselves in respect to formatting

      • reverses text alignment
      • caption is right aligned
      • vertical scroll bars appear on left
      • horizontal scroll bars initialised with slider right-aligned
      • check boxes have CheckAlign property reversed
      • Tab buttons reversed
      • item alignment in list boxes and combo boxes reversed
    • No - controls take normal formatting

    • Inherit - the default value, inherit setting from Form

  • Content of controls with RightToLeft set to Yes is not reversed - i.e. alignment of control changes but text displayed as read from left-to-right. Must format strings manually.

Character Encodings

  • .NET uses Unicode UTF-16
  • Supports legacy formats, e.g. Single-Byte, Double Byte and Bidirectional
  • Encoding conversions via Encoding class obtained by calling Encoding.GetEncoding()
// Code page 932 represents Japanese chars  
Encoding myEncoding = Encoding.GetEncoding(932);
  • Use Encoding instance to convert chars to Unicode (and visa versa) via Encoding.Convert(). Takes source encoding, target encoding and array of bytes
// Obtain encoding instances  
byte[] tgtData;

Encoding srcEncoding = Encoding.GetEncoding(932);
UnicodeEncoding tgtEncoding = new UnicodeEncoding();

// Convert legacy data (in mystring) to bytes
byte[] myData = srcEncoding.GetBytes(myString);

// Perform conversion
tgtData = Encoding.Convert(srcEncoding, tgtEncoding, myData);
  • Use GetChars to convert array of bytes to array of chars
UnicodeEncoding myEncoding = new UnicodeEncoding();

char[] myChars;

myChars = myEncoding.GetChars(myBytes);

Downloads