Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

System Programming

40K

Solutions

19K

Contributors

Kernel and system programming is the process of creating the software necessary for a computer or device to function and operate other programs. Some operating systems (such as Microsoft Windows) are proprietary, but others, such as the various Linux distributions, are open source.

Share tech news, updates, or what's on your mind.

Sign up to Post

Ready to get certified? Check out some courses that help you prepare for third-party exams.
5
Learn how to optimize MySQL for your business need
LVL 3
Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

In this post we will learn different types of Android Layout and some basics of an Android App.
0
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
9
 
LVL 9

Expert Comment

by:Brandon Lyon
Comment Utility
Thanks for the info
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
Nice article!

I'm one of those poor souls who has to write cross-platform C++ code and the headaches involved in getting Unicode encoding working in a cross platform way is a nightmare. In general, we stick to UTF8 right up until we hit the system functions. On *nix platforms UTF8 works fine, on Windows one has to convert to UTF16. It's a bit of a pain, because there is a little inefficiency in doing this but it's normally not enough to cause concern.

What doesn't help is the fact Microsoft continuously refer to UTF16 as Unicode and anything else as ANSI. This has confused a lot of Windows programmers into thinking if it's a 16 bit data type it must be Unicode and if it's an 8 bit data type it's not. Ironically, Windows has no native support for UTF8 at the API level, even though it does have a UTF8 code page! I wish someone would welcome Microsoft into the 21st Century :)

UTF8 is really the only portable encoding format and for my money it's the encoding format I'd go for every time. Anyone interested in Unicode transformation and encoding, either because they are an engineer or they are a masochist, should also find the following resource really very useful and a nice compliment to this well written article.

http://utf8everywhere.org/

Thanks, Gonzo.
0
Exception Handling is in the core of any application that is able to dignify its name.
In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
2
If you use Adobe Reader X it is possible you can't open OLE PDF documents in the standard.
The reason is the 'save box mode' in adobe reader X.

Many people think the protected Mode of adobe reader x is only to stop the write access.
But this feature blocks the open access for OLE documentes too.

OLE by design means that you open a document for instant access for reading and writing.
You take only a reader for your access, but a OLE document every time needs and order write access,
if you chage the document or not.


So it's not only if you want to write to PDF documents, but also, if you want to open OLE PDF documents it's doesn't work too.

You can solve this problem one or two ways:

1. deactivate the 'save box mode' :
- open adobe readerX
- go to menu EDIT-Preferences
- change to categorie GENERAL
- deactivate the point "Enable Protected Mode at Startup"
- click yes if the question comes if you sure to change the prereferences
- save the changes  with OK
- restart the adobe acrobat reader now or later and the changes wil be take affect
Now you can open older OLE PDF documentes and create new OLE PDF documentes e.g in your database

or

2. Do not use OLE documents,
Use packaged documents in the registry for PDF (for future documentes).
For older documents it's not possible to go this way, but you can save a OLD PDF document, after you change  the registry entries from OLE to package document and after this you create a new package document …
0

Introduction:

Dialogs (2) modeless dialog and a worker thread.  Handling data shared between threads.  Recursive functions.

Continuing from the tenth article about sudoku.  

Last article we worked with a modal dialog to help maintain information in the database.  This time we will be working with a modeless dialog to help ‘solve’ a game of Sudoku.  That assistance is provided in a worker thread.

From the resource editor add a new dialog and change the caption to ‘Solve’ (properties menu of the dialog) and the ID to ID_DLG_SOLVE.  A modeless dialog needs the default OK and Cancel behaviours to be stopped. The default behaviour calls EndDialog which is not what should happen, the dialog should be dismissed with a call to DestroyWindow.  From the resource editor, on this new dialog, double click on the OK button.  The add new class wizard should start, enter CDlgSolve as the name and leave other options as defaults.  Click finish and the .h and .cpp files are created for us.  You might notice that no OnOK handler was created – so go back to the resource editor and double click the OK button again.  Now we have a function OnBnClickedOk() (earlier versions of Visual Studio created an OnOK function) which has one line of code – OnOK();  We need to comment this line out.  Repeat for the Cancel button so we have the following:

void CDlgSolve::OnBnClickedOk()
{
    // modeless dialog - do not call OnOK
    //OnOK();
}

void CDlgSolve::OnBnClickedCancel()
{

Open in new window

1

Introduction:

Dialogs (1) modal - maintaining the database.

Continuing from the ninth article about sudoku.  

You might have heard of modal and modeless dialogs.  Here with this Sudoku application will we use one of each type: a modal dialog to help with maintaining the database and a modeless dialog for helping ‘solve’ a game.  The solving procedure will be the subject of the next article so we will just concentrate on the modal dialog and the database maintenance in this article.

Add a new dialog resource in the resource editor and change the ID to IDD_DLG_MAINTAIN and the caption to Maintenance (properties of the dialog).  Then add a list control, three buttons and a picture control.  Select the list control and in the properties make certain ‘Always Show Selection’ is true, ‘No Sort Header’ is true, ‘Single Selection’ is false, ‘Sort’ is none and ‘View’ is report.  Select the first button, change the ID to IDC_BUTTON_EXPORT and the caption to Export.  The second button has the ID to be IDC_BUTTON_IMPORT and the caption as Import.  The third button is IDC_BUTTON_DELETE and Delete as the caption.  The picture control we have an ID of IDC_STATIC_BOUNDARY and make certain the ‘Type’ is Frame.

Resource editor
You can use the buttons in the resource editor to help align (all four sides) and position controls.  The picture above is how I have the dialog layout in the resource editor.  Also delete the two buttons (OK and Cancel) that were on the …
0

Introduction:

The undo support, implementing a stack.

Continuing from the eigth article about sudoku.  

We need a mechanism to keep track of the digits entered so as to implement an undo mechanism.  This should be a ‘Last In First Out’ collection – basically a stack.  MFC supplies various collections, unfortunately a stack is not one of them.  We require what digit was the previous value and to which button.  Where to implement this?  Typically a document would be for the data storage but we are not implementing Sudoku in that way.  Here the buttons themselves (on the view) store the information – so I will implement this undo feature in the view.  An alternative would have been to store the previous values within each button itself – so all we would require was which button was last changed (but I coded it this way before I had that idea, and this way does work - decisions, choices, for a real application plan, plan PLAN! - there is no substitute for that).

First we need to create a new class – CUndoStack – for the storage mechanism.  Solution explorer, Add class, C++ class, Add – enter CUndoStack as the name and accept the defaults.  Modify the header file to be as follows:

#pragma once

class CUndoStack
{
public:
    CUndoStack(UINT nUndoMessage);
    ~CUndoStack(void);

    void AddItem(CWnd* pWndBtn, int digit);
    void RemoveItem();
    bool HasItems();
    void Reset();

private:
    UINT m_nUndoMessage;

    struct strUndo
    {
        

Open in new window

1

Introduction:

Database storage, where is the exe actually on the disc? Playing a game selected randomly (how to generate random numbers).  Error trapping with try..catch to help the code run even if something goes wrong.

Continuing from the seventh article about sudoku.  

Random number generators.  There is a built in random number function in windows.  For playing our games of sudoku having a good random number generating algorithm isn’t necessary.  For other work it may well be critical, put another way having a poor algorithm could result in you generating rubbish from your application – because the data it is based on was not truly random.  Here we are going to provide a basic class for random number generation using a technique (which is supposed to be good) from literature, specifically about mathematical techniques in programming.  Don’t take this as any implication that the inbuilt routines are poor quality or unreliable.  The source of the algorithm here is referenced in the code.

I have created a new database with Microsoft Access, in Access 2000 format, and called it Sudoku.mdb. The database must be located in the same directory as the exe file.  The database contains one table (Games), this contains two fields ID (auto number, primary key) and GameDetail (Text, 82 char, required=true, Allow zero length=false, indexed=yes – no duplicates).

Open the project in visual studio.  Add a new C++ class (not MFC) to the project via the solution …
1

Introduction:

Hints for the grid button.  Nested classes, templated collections.  Squash that darned bug!

Continuing from the sixth article about sudoku.  

Open the project in visual studio.

First we will finish with the SUD_SETVALUE message as this enables the validity checking (a tiny bit missing from the owner draw in the last article – the code in the owner draw was in place) and provides the base for the hinting mechanism.

Sudoku requires that the numbers 1..9 be placed in a block of nine positions, each digit can only appear once.  The classic version we deal with here has each row as one of these blocks, each column and the 9x9 grid split into 9 3x3 grids, each of which also constitutes a block.  All of this we will be wrapping inside a Grid which will contain all 81 individual cells.  One cell can appear in many blocks.

(Specially shaped blocks and diagonals are not covered with this version of the application – maybe a later version would allow user to define their own area.)  Each of these ‘blocks’ should have the information about the nine positions internally and expose functionality to determine which numbers are or are not used within the block.  They can also return information about the validity of numbers entered – eg. 7 is used twice in a block, which is not a valid solution to sudoku.

We therefore need two new classes, a CGrid and a  CBlock – which contains information about the nine positions.  Inside each cell in the grid we …
1
Industry Leaders: We Want Your Opinion!
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Introduction:

Ownerdraw of the grid button.  A singleton class implentation and usage.

Continuing from the fifth article about sudoku.  

Open the project in visual studio.

Go to the class view – CGridButton should be visible as a class.  Right click and go to the properties.  As in the first article click the button to display the overrides, scroll down to PreSubclassWindow and add a function in the combo box.  The editor window should have GridButton.cpp opened and the following code there:

void CGridButton::PreSubclassWindow()
{
    // TODO: Add your specialized code here and/or call the base class
    CButton::PreSubclassWindow();
}

Open in new window


Change it to the following

void CGridButton::PreSubclassWindow()
{
    ModifyStyle(NULL, BS_OWNERDRAW);
}

Open in new window


Notice we don’t need to call the base class implementation (if you looked at it you find it does nothing).  

A quick aside.  Leave the call to the base class there, put the cursor on that line and press the F9 key.  You should see a red dot to the far left of that line.  Now compile and run and the program should stop executing with a yellow arrow now in the red button.  Press the F11 key (step into) and you see the code in that function – does nothing it says so there.

The ModifyStyle – the first parameter is styles to be removed, we don’t want any removing, the second is styles to add.  We want an owner draw button so we add the style flag to indicate owner draw – BS_OWNERDRAW.

An owner draw crash of the application, a simple debug exercise.  The program now compiles but will crash in running – try it.  Sudoku.exe has triggered a breakpoint.  Now press the continue
1
In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual Studio 2010, which is now in beta.  There are really too many new features to cover in even a long article, so I'm going to single out a few things that I think may have an important impact.

While all of the world seems to be gravitating toward a browser-centric programming model, lots of us programmers in the trenches know that there is still, and always will be, a place for desktop application programs and "thick client" application software.  MFC provides the toolkit for serious desktop application programmers.

The Ribbon
The most visible (visual) additions to MFC is support of a U/I feature that is associated with the slick Vista/Windows 7 "look" -- actually the look of Microsoft Office applications.  That look includes a "ribbon" rather than, or in addition to, an old fashioned menu bar.
A ribbon instead of a menubarNow you can create an MFC application program with the same scatter of gadgets and gizmos at the top.  The "Vista Orb" or "Pearl" (what I think of as the marble) in the top left corner really basically equates to the old "File" menu.  And the "ribbon groups" equate to menus, but in a graphical way that makes them a sort of combination menu and toolbar.

The underlying …
12
 

Expert Comment

by:tullhead
Comment Utility
Great article Dan.  I am just about to commence a 'port' of my App from VS C++ 6.0 IDE up to VS2010 IDE and environment.  Are there any good guides, articles, or postings on EE that give some hints as to a methodology to update an old project and to take advantage of these new GUI elements?  Its great when starting a new App to use the wizard-generated sample as a guide -- but what should I be fore-warned about as far as attempting to changeover the look and feel of my old App?  Thanks.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
Great article Dan.  
I don't understand why MS didn't put something like this together themselves.  
0

Introduction:

Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events.

Continuing from the fourth article about sudoku.  

Open the project in visual studio.

If you run the app then you can manoeuvre from one button to the next along a row with the arrow keys (or the tab, shift+Tab) keys.  However the up/down arrow keys are just acting like the left/right arrow keys.  

Wouldn’t it be nice to move up and down simply with the arrow keys.

We need to override the PreTranslateMessage function in the CSudokuView to do that.  Class view, select class, right click for context menu, properties, then scroll down the override functions and <Add> PreTranslateMessage.

You should see this in the code window

BOOL CSudokuView::PreTranslateMessage(MSG* pMsg)
{
    // TODO: Add your specialized code here and/or call the base class

    return CFormView::PreTranslateMessage(pMsg);
}

Open in new window


We need to add the following code where the TODO line currently is.

    if(pMsg->message == WM_KEYDOWN)
    {
        bool bMove = false;    //an arrow key - don't use default behaviour
        int iFocus = 999;
        switch(pMsg->wParam)
        {
        case VK_UP:
            iFocus = GetBtnFocused() - 9;    //'up' one row of the grid
            bMove = true;
            break;
        case VK_DOWN:
            iFocus = 

Open in new window

1

Introduction:

Displaying information on the statusbar.  

Continuing from the third article about sudoku.  

Open the project in visual studio.

Status bar – let’s display the timestamp there.  We need to get the timestamp from the document so we add one public function there (after the GetGame).  Open SudokuDoc.h and append a new line:

    char* GetGame() { return m_arGame; };
    const CString& GetInfo() { return m_szInfo; };

Open in new window


The view is notified when information is changed so we can use the handler (OnUpdate) to also handle this information.  If one looks in the code in the CMainFrame class then one sees that the statusbar is a child of that window, nothing to do with the view – so we will delegate the actual display of information to the frame window itself.

In the SudokuView.cpp file modify it to be as follows (adding the #include “MainFrm.h” after the existing #include “SudokuView.h”)

#include "SudokuView.h"
#include "MainFrm.h"

Open in new window


Next we modify the OnUpdate function, adding a new line directly after the case statement

    case CSudokuDoc::eLoadGame:
        //Update the status bar on the frame
        static_cast<CMainFrame*>(GetParentFrame())->DisplayStatusInfo(GetDocument()->GetInfo());

Open in new window


The GetParentFrame returns a generic CFrameWnd pointer, we cast this to our specific CMainFrame class which is a derived class from CFrameWnd.  Notice this has a new function – DisplayStatusInfo – which we must now add to the CMainFrame class.  Modify the MainFrm.h file so it is as follows:

public:
    afx_msg void OnClose();
    void DisplayStatusInfo(const CString& szInfo);

Open in new window


Now in the MainFrm.cpp file add at the end of the file the function body:

void CMainFrame::DisplayStatusInfo(const CString& szInfo)
{
}

Open in new window


The program should compile but the status bar needs a little work now.  In the OnCreate function of the CMainFrame there should be the following code:


Open in new window

1

Introduction:

Load and Save to file, Document-View interaction inside the SDI.

Continuing from the second article about sudoku.  

Open the project in visual studio.

From the class view select CSudokuDoc and double click to open the header file.  At the end of the file (before the closing brace) add the following lines:
private:
    char m_arGame[82];
public:
    enum {eLoadGame, eSaveGame};
    char* GetGame() { return m_arGame; };

Open in new window


We are going to store the contents of the grid (81 squares) in the character array.  I have added an extra character to store a terminating null for string manipulation options.  The enum defines two values (eLoadGame and eSaveGame) for usage in the app.  One could just hard code with eg. 1 and 2 but which is more understandable?  Using eLoadGame helps one understand what is going on.

From the class view navigate to the OnNewDocument function of CSudokuDoc, it should be as follows:
BOOL CSudokuDoc::OnNewDocument()
{
    if (!CDocument::OnNewDocument())
        return FALSE;

    // TODO: add reinitialization code here
    // (SDI documents will reuse this document)

    return TRUE;
}

Open in new window


Change the code to the following:
    if (!CDocument::OnNewDocument())
        return FALSE;

    strcpy_s(m_arGame, sizeof(m_arGame), "000000000000000000000000000000000000000000000000000000000000000000000000000000000");
    strcpy_s(m_arGame, sizeof(m_arGame), "073200000090600042001000708000000065000050000810000000104000500260003090000004210");
    UpdateAllViews(NULL, eLoadGame, NULL);

    return TRUE;

Open in new window


The first call to strcpy_s will fill the character array with the character 0 – which is NOT a zero.  The second call is just temporary, it is a basis game of sudoku – we will remove it later.  Then we instruct the view that something in the document has changed, note we pass the eLoadGame as a hint to the view receiving the update information.

Now from the class view with add a new override function – OnUpdate and modify it to be the following:


Open in new window

1

Introduction:

Dynamic window placements and drawing on a form, simple usage of windows registry as a storage place for information.

Continuing from the first article about sudoku.  There we have designed the application and put a lot of user interface elements into place.  Now open the project in visual studio.

Pressing the F5 key to test I get the following on my system:

Basic appNote the scroll bar to the right - not nice is it.  So how do we fix that?

From the class view select CSudokuView in the top tree view and in the list below double click the OnInitialUpdate.  You should spring to the code editor and see the following code:

void CSudokuView::OnInitialUpdate()
{
    CFormView::OnInitialUpdate();
    GetParentFrame()->RecalcLayout();
    ResizeParentToFit();
}

Open in new window


Now change the line ResizeParentToFit(); to ResizeParentToFit(FALSE);  The default parameter (TRUE) will instruct the system to shrink the frame to fit but not to enlarge the frame should that be required.  Changing the parameter to FALSE instructs the function to make the frame fit even if it must be enlarged.

void CSudokuView::OnInitialUpdate()
{
    CFormView::OnInitialUpdate();
    GetParentFrame()->RecalcLayout();
    ResizeParentToFit(FALSE);
}

Open in new window


Now run it again – no scroll bar, but still doesn’t look nice.  Let’s finish the layout with some code to demonstrate how one can do some things outside of the resource editor.

First the …
1
This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.  

Introduction:

Sudoku – love it or hate it, your choice.  We are going to make a small application that you can use to assist you in solving sudoku puzzles, or just to solve them yourself and share with others if you wish.  We will need some sort of form (We will only be concerned with the regular 3x3 grid of 3x3 squares, odd shaped groupings, diagonals… will not be covered, at least not in the planned articles, maybe later).  Owner drawing of controls on the form and organisation by code will be demonstrated.  

We will need options to save and load a game (that is not yet finished).  A database to allow you to play random games would be nice.  With the database storage it would be nice to be able to import and export multiple games for sharing.  How about the option to undo the last action – wait why just the last action? Why not a listing of the last changes made and be able to undo lots of changes.  To help you play we will be implementing visual assists – different levels of assistance no less.  

Using Visual Studio – We will be using Visual Studio 2005 for this project and the uploaded files and description of steps here will be based on that.    Database storage will be with Microsoft Access 2000.  Please note that for …
3
 
LVL 40

Administrative Comment

by:evilrix
Comment Utility
Hi Andy,

Just a note to confirm I will be finding some time at the weekend to start reviewing you mammoth article submission. Rather than review them all in one go I think we should focus on one at a time and get it published and then move onto the next. Please let me know if you are okay with this strategy or if you have a preferred manner in which you'd like to work. Obviously. I plan to start with this one first.

Also, what is the ultimate goal for these articles? I mean, do you just want me to give them a quick review to make sure they meet the minimum requirements for publishing or are you hoping to get them awarded EE Approved and, maybe, Editors Choice? The former will require the articles to be above average in terms of presentation and content. The latter is the cream of the crop and will require (potentially) a lot of work from both of us.

Here's the points breakdown for Articles:

Publishing an Article: 500 points
Community Voting: 50 points per helpful vote
Community Picks: 500 points after 10 net helpful votes (or selected by Page Editor)
EE Approval: 4,000 points (selected by PE)
Editors Choice: 5,000 points (selected by PE)

We can, if you like, initially work just to get them published and retrospectively improve them (as necessary) to attain the additional accolades - so it can be done over some time rather than feeling the pressure to complete any additional work up front. As your editor I am happy to do and little or as much to assist you with these articles as you are happy with. Of course to attain EEA and/or EC I will need to be more through in my review, which may (or may not - just preparing you for the worse :> ) result in a lot of constructive criticism and feedback. A simple minimum requirements review is; however, likely to be a relatively pain free process -- all that is required is that any glaring technical inaccuracies, spelling or extreme grammar issues be resolved.

Please let me know how you'd like to proceed.

Thanks.

evilrix
EE Page Editor
0
Here is how to use MFC's automatic Radio Button handling in your dialog boxes and forms.  Beginner programmers usually start with a OnClick handler for each radio button and that's just not the right way to go.  MFC has a very cool system for handling this, but the documentation is a bit unclear, and it helps to see the whole system in action.  

I'll also show a useful technique of creating an enumeration variable to simplify identification and processing of the selected option.  And I'll describe how to disable sub-items that are related to just one of the radio-button options to give your U/I that truly professional look.
Example Dialog or FormIn a "settings" dialog, you will typically need to present your user with several options related to a particular activity.  When you have a largish number, say 4 or 5, then you will display a listbox or a combobox -- especially if that set of options might grow in future versions of your program.  

But when there are only two or three options, it's usually best to show a set of Radio Buttons in your dialog (BTW... Never use a radio button when there is only one option -- use a checkbox instead).

MFC provides the tools, but the Wizard support is a bit finicky -- you need to do things in the right order if you want the Wizard to work for you,  You can also add the radio-group handling manually, but it's worth knowing The MFC way.

1

Use the Dialog Editor to design the form.
In the example, there are three…
4

System Programming

40K

Solutions

19K

Contributors

Kernel and system programming is the process of creating the software necessary for a computer or device to function and operate other programs. Some operating systems (such as Microsoft Windows) are proprietary, but others, such as the various Linux distributions, are open source.