Free SliderList control (kinetic scrollable list with functional items) - Windows Mobile Software Development

Hi all!
I've written a small library and hope it is useful for some other software developers, too. As I got so many hints/tweaks/apps from xda-devs for free, I also want to give this lib out for free. But that does not mean that you are not welcome to donate if you like my work
Attached to this post you will find a zip file containing the library and a demo project showing the capabilities of the library.
As you can see on the screen shots below, the list items can be simple text, check items with and without thumbnail and radio items. All items can be grouped, but do not have to. If you use grouping, you can decide, if the group is collapsible/expandable or not (see also screen shots)
Each item may have ChildItems (despite to the group items, which have *SubItems*). The child items slide in view either by using a ParentItem, which has a "button" to scroll the children in view, or by sliding the finger from right to left after tapping on the item.
If you need another functionality for your item, you can either inherit and extend the item that fits best, or implement IItem on your own.
Of course you can use any graphics you like to skin the list items. To see how it all works, please have a look at the demo project.
I hope this helps others a little bit!
Best regards,
Obelix
FOR DETAILED INFORMATION SEE NEXT POSTING.
Thanks a lot to my friend amird, who spent hours of his spare time to convert my sample from C# to VB. The sample is also available for download here. If you VB users want to contribute for his hard work, please use this thread to find his paypal button
Changelog:
2.3 improved click stability (list won't move while clicking)
2.2 minor changes
2.1
TextItem can now have empty text
fixed: Exception if SliderList has no items
2.0
GroupItems have events for Before-/AfterCollapse and Expand
SliderList has events for Before-/AfterSlideToChildren and -Parent
VirtualMode for SliderList (not internally managed items for a huge number of items)
1.8 HeadlineItems don't care about text, only if Color and Font are set
1.7 Added new Items: HeadlineCheckItem and HeadlineRadioItem
1.6 New Item: ControlHostItem
1.5
sliderList.Recalculate is now public (was internal)
OnItemFocused fired when FocusedItem is manually set
1.4 GroupItems have now published property SubItems
1.3
CheckItem Property: CompleteItemCheck (to check/uncheck the item by clicking anywhere (not thumbnail) on the item
internal Recalculate() in SLiderList. Used by GroupItem to be sure after adding/removing SubItems to have the internal list parameters recalculated
1.2
new methods (see next Post)
GroupItem and RadioGroupItem constructor changed and problem fixed when used in a ChildItem list
pInvoke added (BasItem) to exactly calculate multi line text height in TextItem
Static string SliderList.Version to get the current Version (would be nice to see this in your about screens )
Used some Invokes to make it WM5 compatible and thread save
1.1 event chain changed
1.0 Initial release
If you like my work, you can buy me a glass of wine

Some annotations and sources...
- To skin the control you can use PNG graphics. The transparent color will be the bottom right pixel.
- If you use a graphic as background the height of the item is determined my the bitmap.
- If you inherit from TextItem (as it is done by CheckItem) you have to specify the textRect for the underlying item to render the text correctly.
- the SliderList has an event OnFocusedControl that is fired after tipping on an IItem. After this event the event chain for the items is fired.
SLIDERLIST EVENTS:
event OnItemFocused
is fired when an item is clicked
event BeforeSlideToChildren OnBeforeSlideToChildren
is fired fired before the list slides to ChildItems of the focused item.
event BeforeSlideToParent OnBeforeSlideToParent
if fired before the list slides from the ChildItems back to the parent.
event AfterSlideToChildren OnAfterSlideToChildren
is fired fired after the list slided to the ChildItems
event AfterSlideToParent OnAfterSlideToParent
is fired after the list slided back to the ParentItem.
event GetMaxHeight OnGetMaxHeight
is fired in VirtualMode to determin some values.
event GetItem OnGetItem
is fired in VirtualMode to get the currently rendered item.
event GetIndexOf OnGetIndexOf
is fired in VirtualMode to determin the index of an item for the SliderList
SLIDERLIST PROPERTIES:
List<IItem> Items { get; }
Retrieves the list of items.
bool ShowIndicator
Determines if the indicator bar (Scrollbar) is shown
Color IndicatorColor
The color of the indicator.
Bitmap IndicatorBitmap
Is used as the list indicator. If this is used, the height of the indicator is determined by the height of the bitmap. The indicator color is ignored.
int TopIndex
The index of the IItem that is shown on top of the list.
IItem FocusedItem
The IItem that is currently focused.
Image BackgroundImage
The background image to use.
SLIDERLIST METHODS:
void AddItem( IItem Item )
Add one item to the list
void RemoveItem( IItem Item )
Removed the item from the list
void IndexOf( IItem Item )
Get the index of the item.
void InsertItem( int Index, IItem Item )
Inserts the Item at Index position.
void Clear()
Clears the list of items.
void SlideToChildren()
If the focused IItem has children, the list slides to the left and from the right the list with the children appears.
void SlideToParent()
When a list with children is displayed, it slides out to the right and the list with its parent item appears from the left.
void ScrollInView( IItem Item )
Ensure that the IItem is visible (this could be improved, because the IItem will always be the top item)
void BeginUpdate()
Prevent the list from updating while adding/removing items. If you call it twice, you also have to call EndUpdate twice before the list invalidates itself.
void EndUpdate()
Internally counts back how many BeginUpdate were called. If non is left the control invalidates.
internal Recalculate()
Used by GroupItem to be sure after adding/removing SubItems to have the internal list parameters recalculated
void StartVirtualMode()
Starts the virtual mode. Can be called whenever changed on the items were made to reflect the changed in the SliderList.
ITEMS
IItem interface
Implement this interface for own items.
Additional to the events and properties of IItem the items can have own events, methods and propertis
BaseItem
Bitmap Background : the background image that is used. If background image is used, the item height is determined by the image. Otherwise it can be set by property or constructor.
TextItem
string Text : the text to draw.
Font Font : the font to draw the text.
Color TextColor : the text color.
protected Rectangle textRect : internal used rectangle in which the text is drawn.
RadioItem (derived from TextItem)
Bitmap IconUnchecked : the bitmap displayed right hand side of the item as unchecked state
Bitmap IconChecked : the bitmap displayed right hand side of the item as checked state.
bool Checked : get/set checked state.
CheckItem (derived from TextItem)
event ItemChecked OnItemChecked : fired by cheking/unchecking the item
event ThumbnailClicked OnThumbnailClicked : fired by clicking on the thumbnail (if set)
Bitmap Thumbnail : the image that is displayed left hand side (if not set the corresponding event cannot be fired)
Bitmap IconUnchecked : the bitmap displayed right hand side of the item as unchecked state
Bitmap IconChecked : the bitmap displayed right hand side of the item as checked state.
bool Checked : get/set checked state.
bool CompleteItemCheck : get/set whether to check/uncheck the item by clicking anywhere (not thumbnail) on the item
ParentItem (derived from TextItem)
event ThumbnailClicked OnThumbnailClicked : fired by clicking on the thumbnail (if set)
Bitmap Thumbnail : the image that is displayed left hand side (if not set the corresponding event cannot be fired)
Bitmap IconShowMore : the icon used to indicate that children are available.
when clicked on that bitmap the list slides automatically to the childrens list.
GroupItem (derived from TextItem)
BeforeCollapseOrExpand OnBeforeCollapseOrExpand : fired before items is collapsed or expanded.
event AfterCollapseOrExpand OnAfterCollapseOrExpand : fired after item is collapsed or expanded.
Bitmap IconExpanded : the icon used to indicate the list can be collapsed.
Bitmap IconCollapsed : the icon used to indicate the list can be expanded.
bool Expanded : get/set the expanded/collapsed state
AddSubItem( IItem SubItem ) : add a new item to the group.
RemoveSubItem( IItem SubItem ) : remove an item from the group
List<IItem>SubItems : gets the IItems list of this group. Don't forget to call sliderList.Recalculate() after changing the list directly!
RadioGroupItem (derived from GroupItem)
takes care that only one RadioItem can be checked. Other items are allowed in that list.
ControlHostItem
Control Control : the control to be hosted (may be TextBox or UserControl. See DemoProject)
depending on the guest control scrolling may be slow!
HeadlineCheckItem (derived from TextItem)
same settings as CheckItem
Font HeadlineFont (must be set to get headline displayed)
Color HeadlineColor (must be set to get headline displayed)
String HeadlineText
HeadlineRadioItem (derived from TextItem)
same settings as RadioItem
Font HeadlineFont (must be set to get headline displayed)
Color HeadlineColor (must be set to get headline displayed)
String HeadlineText
As example for extending the control with own items I post the source of CheckItem here.
The most common problems
using the items and not setting the Font property!
Using GroupItems and not adding them to the SliderList before adding SubItems to the group
Using Headline items and not setting Font/Color/Text for the Headline (results in headline not drawn)
Have fun!
Obelix

for German speaking developers: http://www.pocketpc.ch/news/78204-fuer-entwickler-innen-sliderlist-control.html

Very cool.

... thanks!
I thought nobody will comment in any way...
I hope some suggestions and hints will show up. Maybe devs will use it in real world apps and will post screen shots and links to their software.

Thank Obelix_A nice work !

Thanxs for your hard work

how to use?

looks nice. will try it in one of my next projects!

Thank you! Very good! Whether you plan to make library with an open source?
P.S. Sorry, my English is so bad.
P.P.S. ClickedItem example:
Code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using Microsoft.Drawing;
namespace ARBOControls.PPC.SliderList
{
public delegate void ItemClicked(IItem Item);
public class ClickedItem : TextItem
{
public event ItemClicked OnItemClicked;
public Bitmap Thumbnail { get; set; }
protected Rectangle ThumbRect = new Rectangle(-1, -1, -1, -1);
public ClickedItem(SliderList SL)
: base(SL)
{
}
#region IItem Members
public override void Paint(System.Drawing.Graphics G, int Top, int Width)
{
int lMargin = 3;
int thumbWidth = 0;
if (Thumbnail != null)
{
int h = Thumbnail.Height;
thumbWidth = Thumbnail.Width;
lMargin = (this.height - h) / 2;
ThumbRect = new Rectangle(lMargin, Top + lMargin, Thumbnail.Width, Thumbnail.Height);
}
int rMargin = 3;
int bWidth = 0;
textRect = new Rectangle(2 * lMargin + thumbWidth, Top + 4, Width - (2 * lMargin + thumbWidth) - (2 * rMargin + bWidth), height - 9);
base.Paint(G, Top, Width);
if (Thumbnail != null)
G.DrawImageTransparent(Thumbnail, ThumbRect);
}
public override void Click(Point Position)
{
base.Click(Position);
if (OnItemClicked != null)
OnItemClicked(this);
}
#endregion
}
}

wei2005yh said:
how to use?
Click to expand...
Click to collapse
...download the demo project from the 2nd post and have a look at the source. If anything left unclear please ask a more specific question. I will answer as good as I can

Obelix_A: What else can I say!! Thanks!
Looks very impressive and you have surely put in a lot of hard work creating this library.
When I start my next project, I will try them out.
Once again, many thanks!

Thanks! It's great!

This looks VERY nice mate. Thanks for your hard work.
If there was a cross-over between michyprima's manila SDK and your work, that would be fantastic!

looks awsome. This will help with my learning. Thank you very much.

Obelix_A said:
...download the demo project from the 2nd post and have a look at the source. If anything left unclear please ask a more specific question. I will answer as good as I can
Click to expand...
Click to collapse
ok I see ,thank you..

How to determine the SelectedItem
Hi,
This looks very promisefull. But how can I check which item is selected or changed in the Sliderlist.
Nico

Hi Nico,
by catching the OnItemFocused event from the list you get the last selected/focused item

Looking very promising, going to check it up.
Thanks mate...

very nice work! thx a lot

Related

Size of Form

Hello,
i have an application, programmed in C#. I wanna that the size of the gui will automatically adapt to the size of the phone on which the application get used.
How can I do this?
In the Paint() event of the form examine its ClientSize property. This is the size of the client (White) area of the screen. It is itself a Size object with Height and Width integer properties, this.ClientSize.Width and this.ClientSize.Height
Use these values to position/resize your objects on the screen, by changing their Size and Location (Left and Top) properties, so that they fit in this area.
This event occurs before the Paint() event of the child objects, so they will be repositioned/resized before they themselves are drawn.
To be clever, reposition and resize screen objects, scaled to the screen size at run time, not values hardcoded at development time.
This technique can also detect a change of orientation, the values of Height and Width change over! If you want to be smart, handle this as well, and your app should be starting look pretty damned professional. A bit of work and it should look good on all screen sizes. Test them out against the SDK's emulator images for a range of device screen sizes.
The following code example positions the label in the correct place. Hey Diddle Diddle, slap bang in the middle!
Code:
private void Form1_Paint(object sender, PaintEventArgs e)
{
label1.Left = (this.ClientSize.Width - label1.Size.Width) / 2;
label1.Top = (this.ClientSize.Height - label1.Size.Height) / 2;
label1.Text = this.ClientSize.Width.ToString() + " x " + this.ClientSize.Height.ToString();
}
do you have to do this with every object you put on it? Seems like a lot of code. (also im doing this in VB so far..)
I'm afraid so. But it's worth the effort. Also it will run on all screen sizes, see image, and also the oddball ones they haven't thought of yet!
Change 'this.' to 'me.' and omit the C# end of line character ';' and it's now in VB.
Does your form property AutoScaleMode is set to AutoScaleMode.Dpi?
For controls set the anchor property (default is top|left) also to right (and/or bottom if needed). That will automatically 'stretch' the controls.
Advanced:
Now, if you really want to support different resolutions it will take much more work:
As already mentioned you have to rearrange the controls on orientation changes. Take a look at Developing Orientation and dpi Aware Applications for the .NET Compact Framework!
And finally you have to provide images in different resolutions.
Adapt to New Screen Orientations and Resolutions
Of course you have to decide if this is really needed for your app as this will take much more time.

[Q] VB and the ApplicationBar

Using VB, im trying to add an application bar in the code (rather than xaml). I have the following code:
Code:
Public Sub New()
InitializeComponent()
Dim appBar As ApplicationBar
appBar = New ApplicationBar
appBar.IsMenuEnabled = True
appBar.IsVisible = True
appBar.Opacity = 1
Dim icon As New Uri("/Images/expand.png", UriKind.Relative)
Dim cmdStart As New ApplicationBarIconButton(icon)
cmdStart.Text = "Start"
'AddHandler (cmdStart.Click), test_click()
appBar.Buttons.Add(cmdStart)
' Set the data context of the listbox control to the sample data
DataContext = App.ViewModel
End Sub
However when i run it in the emulator there is no application bar! No error either. It is a pivot application also but this shouldnt make a difference surely? any ideas?
The application bar is accessible via the ApplicationBar property of the Page class you're deriving from. You don't need to create your own instance.
Thanks, I actually figured this out just after i posted the question. Thanks anyway.

[Q][Solved] Messagebox.yesno not displaying it's buttons [VB.Net]

Really quick question. I'm coding a messagebox with some yes/no buttons but when i test it the buttons are not drawn (see picture and code below). Any ideas?
Code:
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] File.Exists(dirpath1) [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] MsgBoxQ = [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"file exists. Overwrite"[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] Msg = MessageBox.Show(MsgBoxQ, MessageBoxButtons.YesNo)[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] Msg = DialogResult.Yes [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]GoTo[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] writefile[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]ElseIf[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] Msg = DialogResult.No [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]MessageBox.Show([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Operation Canceled By user"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Exit[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE]
[/COLOR][/SIZE]
Check out the different overloads of the Show method:
MessageBox class
You are using the one with two strings text and caption (the 4 in the caption is the enum YesNo converted to a string)
Just provide the caption text as second parameter and the YesNo as third.
heliosdev said:
Check out the different overloads of the Show method:
MessageBox class
You are using the one with two strings text and caption (the 4 in the caption is the enum YesNo converted to a string)
Just provide the caption text as second parameter and the YesNo as third.
Click to expand...
Click to collapse
Errrr ok. I'll read the page again and post back if i'm still stuck.
HeliosDev, You are partly correct but there are 2 extra options that aren't defined in the MSDN example which must be set. These are MessageBoxIcon and MessageBoxDefaultButton.
Anyway, thanks for helping.

How make HELLO WORLD on the WM6.1 ???

Who can write Step by Step instruction by C++/VisualStudio 2008 ? for writing Hello World apps And simple actions of work with forms???
You can start here...http://www.hitmill.com/programming/cpp/helloWorld.htm
Remember a search engine is your friend.
Hope that I have help you.
In C++ you have the choice of WIN 32, ATL and MFC programming models. They are all different.
If you are using standard windows forms items ie buttons, editboxes, dropdowns etc. C# is a LOT easier.
stephj said:
If you are using standard windows forms items ie buttons, editboxes, dropdowns etc. C# is a LOT easier.
Click to expand...
Click to collapse
It is indeed much easier for "Hello World" type applications. For more complicated things, poor performance and lack of direct access to the native API begins to add up.
The original poster probably has some specific problem, the solution to which he hopes to find in a step-by-step tutorial. If he still has not been able to solve it, it might help to describe it to us.
O.K........
Over the next few posts, (Rome wasn't built in a day!), this will build into a step by step tutorial in how to create a basic WIN32 application. As a start we will use the C# .Net solution I wrote in reply to this post:
http://forum.xda-developers.com/showthread.php?t=1435629
The original request was for an application that calculates the check digit for an intermodal container number. For the uninitiated, intermodal containers are the ubiquitous 20ft and 40ft metal boxes that dominate the shipping industry.
All containers have an eleven digit serial number of the form:
ABCD 123456 7
Where ABC is the code for the container's owner, and D is the Category Identifier, almost always a 'U'. 123456 is the serial number of the box and the final number '7' is the checksum digit which is calculated from the previous 10 characters. When keying in container numbers into computer systems etc, it can be used to quickly check whether the container number is valid before further processing is done. The same thing applies to the last digit of your credit card number, it is calculated from the previous 15 numbers.
Container numbers conform to ISO6346 and more can be read here http://en.wikipedia.org/wiki/ISO_6346
We will build a WIN32 C++ Mobile 6 application to calculate the check digit from those given in a text box on the screen.
Validation will be minimal, if the user enters anything but characters of the form AAAA999999 in the textbox, nothing appears in the check digit box. When valid, the checkdigit magically appears.
You will need:- Visual Studio Professional 2008, not the express version, and an installed Windows Mobile 6.0 SDK
The Express version of VS cannot target mobile devices. VS 2003/5 can also be used, as well as earlier or later versions of the SDK, but you will encounter slight differences in VS or the SDK, that you will have to fight your way through yourself.
The finished application will look something like the attached image.
Under Win32, there is no drag and drop toolbox, all controls have to be created from scratch. All good fun, so roll up your sleeves, break out the birch twigs and let the self-flagellation begin.......
Right!.....Let's go............
From VS2008 select
File -> New -> Project
Select C++, Smart Device and Win32 Smart Device Project. Select the destination for the project and name it IS06346. See image 01.
Click OK
On the Platforms submenu of the next screen add the Windows Mobile 6.0 SDK to the project and remove the others. See image 02
........and, on the 'Application Settings' submenu, make sure the Windows Application radio button is on, and all others are off. See image 03
Click Finish. The VS wizard will create all the basic files we need under the directory given above.
In fact, pressing F5 should build this project and run it in the emulator. The application does very little at this stage, nothing to be precise, but it should work........... See 04
The main program is ISO3486.cpp This shell program is some 250 lines of code, most of it is needed for a "do nothing" program, but it boils down into five main functions.
WinMain() The entry point of the program, where the operating system will call it on initial load. Leave it alone.
InitInstance() Called immediately by WinMain and where the program creates its initial window etc. We will add a few bits of extra initialization here.
MyRegisterClass() Called by InitInstance to register the window class, just before the initial window is created. Leave it alone unless you really know what you are doing.
WndProc() The message processing loop for the main/parent window. Any windows event will be fired at this function as a Windows Message, it is up to us to process the ones we need. A few variables will go in here. All the original WM2003 "Hello World" program did, in the EVC based SDK, was to intercept the WM_PAINT message, find the client area of the screen, and draw the text "Hello World" in the middle of it.
About() The message processing loop for the About dialog box. We will be quite happy with the default action so we'll leave it alone.
To Do:
1.) Add reference to <string.h>
2.) Create two text boxes and display them. Limit the entry to 10 characters on the main edit box and disable input on the second check digit box.
3) Draw an "Enter container number:" text label above the edit boxes in response to the WM_PAINT message. The edit boxes will draw themselves when required.
4.) Intercept the EN_CHANGE message from the main edit box. If the length of the text in the box is 10 characters long, uppercase it, and if it is valid, generate the checksum and display it in the checksum box, otherwise clear the checksum box. Replace the textbox text with its uppercase value, but do not respond the the EN_CHANGE message generated by this change, as this will trigger an infinite shower of EN_CHANGE messages.
When this is done, we will have a working application.
To be continued.....................
Next...........
Let’s work our way down the TODO: list above.
1.) Add reference to “string.h”:
Later on we are going to use a call to towupper() to convert the input into uppercase. It is defined in string.h, so we have to add this to the source file.
At the top of the ISO6346.CPP after the line
Code:
#include "ISO6346.h"
Add the line:
Code:
#include "string.h"
2.) Create two text boxes and display them......
We will create two windows as text boxes, but we will save their handles as global variables as they are referenced from more than one function. While we are at it we also need a global Boolean variable to prevent the uppercased replacement from causing the runaway reaction mentioned above.
After:
Code:
HINSTANCE g_hInst; // current instance
HWND g_hWndMenuBar; // menu bar handle
Add:
Code:
HWND g_hWndText,g_hWndCheck;
bool g_Updating;
Now let’s create the text edit boxes. You may already know this, or this may be an eye opener, but all edit controls are actually windows in their own right, albeit that they are child windows of the main form.
In InitInstance() after:
Code:
if (!hWnd)
{
return FALSE;
}
add:
Code:
g_hWndText= CreateWindow(TEXT("EDIT"),NULL,WS_CHILD | WS_BORDER,40,50,110,20,hWnd,NULL,hInstance,NULL);
g_hWndCheck=CreateWindow(TEXT("EDIT"),NULL,WS_CHILD | WS_BORDER, 160,50,20,20,hWnd,NULL,hInstance,NULL);
This creates the text edit boxes. As yet they won’t be displayed, but we have to tweak them first. We want to disable the checkdigit box, so that the user cannot type anything into it as we will set it with the correct value when a valid container number is entered in the text box. We will disable it by calling the EnableWindow() function.
We also need to set the size of the text edit window to 10 characters. Under MFC and .NET this is a hoot, as it already a property of the edit control object, which has been conveniently wrappered for us, and we can just set that property. Here in the world of Win32, it is not quite so simple. We have to fire an EM_SETLIMITTEXT message at the window, to tell it that that is what we want. While we are at it, let's set the global g_Updating variable to be false, ready for use later, and here is as good a place as any to do it.
After the CreateWindow() lines we have just added, add the next three lines to do the above.
Code:
SendMessage(g_hWndText,EM_SETLIMITTEXT,10,0);
EnableWindow(g_hWndCheck,false);
g_Updating=false;
Now the windows exist as we want them, all we have to do is display them. At the bottom of the InitInstance() function after
Code:
ShowWindow(hWnd, nCmdShow);
add
Code:
ShowWindow(g_hWndText, nCmdShow);
ShowWindow(g_hWndCheck, nCmdShow);
The main window will now look after them and control them as required. Marvellous!
3) Draw an "Enter container number:" text label............
Now we need a label above the two boxes to tell the user to type a valid container number number into the text box. From the resource view of the project, open the String Table folder in ISO6346ppc.rc then open the String Table object. Click in the blank entry at the bottom and change the ID to IDS_ENTER and the Caption to "Enter container number:" Don't worry about the what the value is, if it is not '3', as the IDE will take care of it.
To get it drawn on the form, we will have to add it to the WM_PAINT event of the main window. We'll need a RECT structure to describe where we want the text to go, a buffer to store the string and while we are here let's add the function variables we are going to need later. At the top of the WndProc() function:
After:
Code:
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
add
Code:
TCHAR c,szBuffer[MAX_LOADSTRING];
RECT rt;
int i,j,k;
bool valid;
i,j and k are general variables for calculating the check digit. szBuffer is used to hold the "Enter container number:" string in WM_PAINT, and also for the contents of the edit box when it changes. As these two events will not occur at the same time, we can get away with it having a dual personality. Variable 'c' is used to read the string one character at a time and 'valid' is set to false if the the container number is not in the correct format.
Replace the TODO: line in the WM_PAINT handler
Code:
// TODO: Add any drawing code here...
with:
Code:
rt.top=20;
rt.bottom=40;
rt.left=40;
rt.right=180;
LoadString(g_hInst,IDS_ENTER,szBuffer,MAX_LOADSTRING);
DrawText(hdc,szBuffer,wcslen(szBuffer),&rt,0);
Now when the form is drawn, the label will appear in the right place.
4.) Intercept the EN_CHANGE message from the main edit box..........
There is no easy way to do the next bit step-by-step, so we will just do it, I'll explain later.........
Replace the standard code for the response to the WM_COMMAND message:
Code:
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_HELP_ABOUT:
DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About);
break;
case IDM_OK:
SendMessage (hWnd, WM_CLOSE, 0, 0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
with this:
Code:
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_HELP_ABOUT:
DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
break;
case IDOK:
SendMessage (hWnd, WM_CLOSE, 0, 0);
break;
}
switch (wmEvent)
{
case EN_CHANGE:
if(g_hWndText == (HWND) lParam && !g_Updating)
{
GetWindowText(g_hWndText, szBuffer,MAX_LOADSTRING);
if(wcslen(szBuffer)==10)
{
k=0;
valid=true;
for(i=0; i<10; i++)
{
c=szBuffer[i]=towupper(szBuffer[i]);
if((i<4 && (c<'A' || c>'Z')) || (i>3 && (c<'0' || c>'9')))
valid = false;
j=int(c);
if (j > 64 && j < 91)
k += ((j - 55) + (j - 56) / 10) << i;
else
k += (j - 48) << i;
}
if(valid)
{
// Calculate final check digit
k = ((k % 11) % 10);
// Do not process the following update
g_Updating = true;
SetWindowText(g_hWndText,szBuffer);
g_Updating = false;
// Set check window to correct value
szBuffer[0]='0'+k;
szBuffer[1]='\0';
SetWindowText(g_hWndCheck,szBuffer);
// Position cursor at end of edit field.
SendMessage(g_hWndText,EM_SETSEL,10,10);
}
else
SetWindowText(g_hWndCheck,TEXT(""));
}
else
SetWindowText(g_hWndCheck,TEXT(""));
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
When the text edit box contents are changed, a EN_CHANGE message arrives at the parent window. It appears as a WM_COMMAND message with the wmEvent parameter containing the EN_CHANGE identifier, together with the handle of the window that generated the message. That is why the second 'switch' code exists to trap the EN_CHANGE event message.
If the EN_CHANGE message came from the Text edit window, not the Checksum window, then get the text within it. If the length is 10 characters long, then process the string. The variable k is used as a running total for the checksum. If after processing all 10 characters, the string is still valid, it is converted modulo 11 and then modulo 10 into the final checksum number. The checksum edit box is then updated with this value. The contents of the Edit box are replaced with its uppercase value. In doing so, we will cause another EN_CHANGE message to be sent to the parent window, which would cause this function to be executed again, and so on and so forth, causing an infinite shower of messages. To prevent this, we set the global variable g_Updating to true before making the change, and then setting it to false immediately afterwards. The test in the first line of the EN_CHANGE processing code, does not execute at all if g_Updating is true, thereby preventing this problem.
Build the final program, and test it in the emulator. Switch the build to 'Release' and the target to Windows Mobile Device, and run the executable on your device.
The complete ISO6346.cpp file is included in the attached zip file.
Here endeth the lesson...........
As a continuation, we will build the whole thing again from scratch, but next time using the Microsoft Foundation Class, MFC.
Watch this space..................
Don Reba said:
It is indeed much easier for "Hello World" type applications. For more complicated things, poor performance and lack of direct access to the native API begins to add up.
Click to expand...
Click to collapse
I totally agree with this! And worst thing is you can neither use a resource hacker tool nor a dependency walker tool, if you want to inspect a .NET CF application.
Using MFC......
From VS2008 as before select File->New->Project then select Visual C++, Smart Device, and MFC Smart Device Application.
Name it ISO6346 as before, and click OK. See image 01
On the platforms submenu select the Windows Mobile 6.0 SDK as before. See image 02
On the Application Type submenu, select the "Dialog Based" and "Use MFC in a static Library" radio buttons. See Image 03
By default the application comes with two dialog boxes for portrait and landscape but in our case this is complete overkill. We will get rid of the Landscape (Wide) dialog box.
In the Dialog folder of the resource view of ISO6346ppc.rc, delete the IDD_ISO6346_DIALOG_WIDE entry. See image 04.
To get this past the compiler, we will have to tidy it up a bit. In ISO6346Dlg.cpp delete the following sections of code.
Code:
#if defined(_DEVICE_RESOLUTION_AWARE) && !defined(WIN32_PLATFORM_WFSP)
void CISO6346Dlg::OnSize(UINT /*nType*/, int /*cx*/, int /*cy*/)
{
if (AfxIsDRAEnabled())
{
DRA::RelayoutDialog(
AfxGetResourceHandle(),
this->m_hWnd,
DRA::GetDisplayMode() != DRA::Portrait ?
MAKEINTRESOURCE(IDD_ISO6346_DIALOG_WIDE) :
MAKEINTRESOURCE(IDD_ISO6346_DIALOG));
}
}
#endif
and also:
Code:
#if defined(_DEVICE_RESOLUTION_AWARE) && !defined(WIN32_PLATFORM_WFSP)
ON_WM_SIZE()
#endif
Double Click in the IDD_ISO6346_DIALOG entry to open it up in the main window. Click on the "TODO: Place dialog controls here" label and change its caption to "Enter container number:", and position it near the top of the dialog box. From the Toolbox view, drop two edit controls on to the dialog box, under the above label. See image 05. Right click on the first box and select Add Variable. Name the first box edtText and click Finish. See image 06. Do the same for the second box and name it edtCheck. Notice that the wizard has added entries for the DoDataExchange(CDataExchange* pDX) function.
In OnInitDialog() after the line
Code:
// TODO: Add extra initialization here
Add:
Code:
Updating=false;
edtText.LimitText(10);
edtCheck.SetReadOnly();
Note that an Edit Control has more useful methods to call than the Win32 method above, where setting the text limit of the control has to be done by sending windows messages to it.
Right click on the Text Edit Box control and select "Add event handler..." select the EN_CHANGE message, take the default event handler function name, and click the "Add and Edit" button. See image 07 In ISO6346Dlg.h notice that the wizard has added the two edit boxes at the bottom of the file, and also added the message map thus:
Code:
public:
CEdit edtText;
CEdit edtCheck;
afx_msg void OnEnChangeEdit1();
In the //Implementation section of the same file after
Code:
HICON m_hIcon;
add:
Code:
bool Updating;
This will be used as before to prevent an infinite cascade of messages.
In the OnChangeEdit1() function add the following code:
Code:
int i,j,k;
wchar_t c;
bool valid;
CString strText,strCheck;
if(!Updating)
{
if(edtText.LineLength(0)==10)
{
edtText.GetLine(0,strText.GetBuffer(10),10);
strText.ReleaseBuffer(-1);
strText.MakeUpper();
k=0;
valid = true;
// Check the contents are of the form ABCD123456
for(i=0; i<10; i++)
{
c=strText.GetAt(i);
j=int(c);
if((i<4 && (c<'A' || c>'Z')) || (i>3 && (c<'0' || c>'9')))
valid = false;
if (j > 64 && j < 91)
k += ((j - 55) + (j - 56) / 10) << i;
else
k += (j - 48) << i;
}
if(valid)
{
// Calculate final check digit
k = ((k % 11) % 10);
strCheck.GetBufferSetLength(1);
strCheck.SetAt(0,'0'+k);
strCheck.ReleaseBuffer(-1);
edtCheck.SetWindowTextW(strCheck);
Updating = true;
// Do not process the following update
edtText.SetWindowTextW(strText);
Updating = false;
// Position cursor at end of edit field.
edtText.SetSel(10,10,0);
}
else //Invalid Not ABCD123456 - clear the check digit field
edtCheck.SetWindowTextW(TEXT(""));
}
else // Invalid - Not 10 char long - clear the check digit field
edtCheck.SetWindowTextW(TEXT(""));
}
This time we use CString objects to get/set the contents of the edit controls.
Right! That's it. Compile it and run it, either in the emulator or on the device.
See image 08. Notice that as this a dialog application, there are no menu buttons. When the [X] button is pressed the program terminates.
As another interesting point, compare the sizes of the two release executables. The Win32 version is around 8.5kb, that of the MFC version is around 167kb, both launch pretty damned quickly. Compare that with the . NET C# executable from the original post. That is around 9kb in size, but it takes your device around three seconds to shove it through the JiT compiler in order to able to run it, and that is for only a tiny .NET program.

Hide input panels with setting configuration?

Is there a way to hide certain input panels on the window form using configuration or config file of some sort?
For example.... let's say in my database I have items with 12 possible fields in each (Name, LastName, Age, Occupation, Location.......etc).
But what is a user of application only wants to fill in 3 fields every single time (for example - LastName, Age, Location)? Leaving others in place when user doesn't needs them is an extra clutter. So how can I hide or disable those input panels based on user's preference on which fields he wants to use?
--
I think I found a way to hide items by setting Visible boolean.
Code:
this.txtName.Visible = false;
this.lblName.Visible = false;
this.txtOccupation.Visible = false;
this.lblOccupation.Visible = false;
However, how can I move up other fields between or below them? Currently hiding just creates empty spaces.
You can turn the textbox off completely by setting its enabled property to false.
You can then move other textboxes and labels over it by setting their Location.X and Location.Y properties.
You will have to keep track of where everything is on the screen, and what is enabled and what isn't.
stephj said:
You can turn the textbox off completely by setting its enabled property to false.
You can then move other textboxes and labels over it by setting their Location.X and Location.Y properties.
You will have to keep track of where everything is on the screen, and what is enabled and what isn't.
Click to expand...
Click to collapse
Thanks.
Do you know if there is an easy way to move everything up? (lets say I make first item invisible and want to move the 10 items below up) Or will I have to call everyone individually to move up?
Also.. Is there away how I can use TabIndex to call those forms?
There are others ways to accomplish what you are looking for, but no easy route to it.
They all end up as broad as long. You either spend time during the design stage, creating an array of possible tabbed forms to be used by the program later, or spend time designing the program to deal dynamically with the fields required. The latter of the two is harder to do, but it is far more elegant.
Sorry, but there is no silver bullet.

Categories

Resources