Saturday, November 22, 2014

Change color of an Edit Box upon Set and Kill Focus.


I want to change the color of an Edit box upon set focus and set back to normal color as the focus killed as my client want so. Hope this tricks will help those beginner who want to change their control color.

 

Here is the process I Have follow

 

1.       Create a MFC Dialog based project.

2.       Add following control on the dialog



3.       Add two Global variable for the background and text color and a Static CBrush.

 

const COLORREF FG_COLOR = RGB(186, 186, 186);

const COLORREF BK_COLOR = RGB(69, 69, 69);

static CBrush bkBrush(BK_COLOR);

 

4.       Add WM_CTLCOLOR member function and add following code.

HBRUSH CColorEditDemoDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)

{

                HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);

                if (nCtlColor == CTLCOLOR_EDIT &&

                                pWnd->m_hWnd == ::CWnd::GetFocus()->GetSafeHwnd())

                {

                                pDC->SetBkColor(BK_COLOR);

                                pDC->SetTextColor(FG_COLOR);

                                return bkBrush;

                }

                return hbr;

}

5.       Add Setfocus and KillFocus function on MESSAGE_MAP

BEGIN_MESSAGE_MAP(CColorEditDemoDlg, CDialogEx)

               

                ON_CONTROL_RANGE(EN_SETFOCUS,0x0,0xFFFFFFFF,OnEditSetFocus)

                ON_CONTROL_RANGE(EN_KILLFOCUS,0x0,0xFFFFFFFF,OnEditKillFocus)

END_MESSAGE_MAP()

6.       Add two member function as on Message map. OnEditSetFocus and OnEditKillFocus.

void CColorEditDemoDlg::OnEditSetFocus(UINT nID)

{

                RepaintIfEdit(GetDlgItem(nID));

}

void CColorEditDemoDlg::OnEditKillFocus(UINT nID)

{

                RepaintIfEdit(GetDlgItem(nID));

}

7.       Add a member function RepaintIfEdit (if the focus control is an edit will be repainted.)

void CColorEditDemoDlg::RepaintIfEdit(CWnd* pWnd)

{

                WCHAR clsName[6] = L"";

                GetClassName(pWnd->GetSafeHwnd(), clsName, 6);

                if (StrCmp(clsName, L"Edit") == 0)

                {

                                pWnd->Invalidate();

                                pWnd->UpdateWindow();

                }

}

 

Compile and Run.

You can have demo here.

Tuesday, November 18, 2014

How to Add Tooltip and Balloon Tip on a dialog control

Hello!
Today I will show you how to add a tool tip for dialog control and a balloon tip for an edit box.

  1. Create a MFC Dialog Preject.
  2. Add following control to the dialog.
   
3.   Open BlogTest2Dlg.h and add CToolTipCtrl *m_pToolTip; as private.
Private:
CToolTipCtrl *m_ToolTip;
 
4.      Open BlogTest2Dlg.cpp and add following on OnInitDialog(); function.
BOOL CBlogTest2Dlg::OnInitDialog()
{
                …….
 
     // TODO: Add extra initialization here
     m_pToolTip = new CToolTipCtrl();
     if (!m_pToolTip->Create(this))
     {
           TRACE(L"Unable to create ToolTipCtrl.\r\n");
           return TRUE;
     }
     if (!m_pToolTip->AddTool(GetDlgItem(IDOK), L"This is OK Button."))
     {
           TRACE(L"Unable to add OK Button.");
           return TRUE;
     }
     if (!m_pToolTip->AddTool(GetDlgItem(IDCANCEL), L"This is Cancel Button."))
     {
           TRACE(L"Unable to add Cancel Button.");
           return TRUE;
     }
     if (!m_pToolTip->AddTool(GetDlgItem(IDC_EDIT1), L"Try to insert key '5' and will summon balloon."))
     {
           TRACE(L"Unable to add Edit Control.");
           return TRUE;
     }
     m_pToolTip->Activate(TRUE);

}
5.       Add PreTranslateMessage Function, add following code.
BOOL CBlogTest2Dlg::PreTranslateMessage(MSG* pMsg)
{
                if (m_pToolTip != NULL)
                                m_pToolTip->RelayEvent(pMsg);
                return CDialogEx::PreTranslateMessage(pMsg);
}
Done with ToolTip. Now go for Balloon Tip.
1.       Add a new MFC Class “CBalloonEdit” and the base class is “CEdit” from Class Wizard.
2.       Add WM_CHAR Message handler.
3.       Add following Code OnChar Function.
void CBalloonEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
        if (nChar == 0x35)
        {
                        ShowBalloonTip(L"Unacceptable Character", L"The Number 5 will summon the Balloon.",TTI_INFO);
                        return;
        }
        CEdit::OnChar(nChar, nRepCnt, nFlags);
}
4.       Add CBalloonTip Variable on BlogTest2Dlg.h
CBalloonEdit m_baloonEdit;
Also Include BalloonEdit.h on the BlogTest2Dlg.h
5.       Add following code to
void CBlogTest2Dlg::DoDataExchange(CDataExchange* pDX)
{
        CDialogEx::DoDataExchange(pDX);
        DDX_Control(pDX, IDC_EDIT1, m_baloonEdit);
}
 
Now build and run the program. You should have following output.
 
 
Thanks.

Sunday, November 16, 2014

Making a Dialog Topmost and Resizable.


You may have seen windows that stay on top of all others no matter what is placed on top of them (these are often tool boxes and palettes), and you may wonder how that works, The answer is that the window has been made a topmost window, and we can make our window topmost with the click of a button or initially. Besides we can hide a portion of a dialog boxes unless they are needed. The only problem with resizing our dialog window is that we might start thinking in terms of pixel measurements of widths and heights—but that means different things on different screens. In other words, if we pugged numbers into SetWindowPos() like this to contract our dialog window, those pixel measurements’ would mean different things on different resolution screens:

Dialog boxes themselves are designed in nits that attempt to avoid this problem. If you look in xxx.RC, you’ll find our main window designed this way in the resource templates:

IDD_XXX_DIALOG DIALOGEX 0, 0, 208, 105    

   STYLE DS_MODALFRAME|WS_POPUP|WS_VISIBLE|WS_CAPTION |WS_SYSMENU

EXSTYLE WS_EX_APPWINDOW

CAPTION “Your Dialog caption”

FONT 8, “MS Sans Serif”

BEGIN

       DEFPUSHBUTON    “OK”, IDOK, 110, 10, 48, 17
       PUSHBUTTON      “Cancel” IDCANCEL, 110, 25, 48, 17

END

 This measurements are in special dialog-box units instead of pixels. The horizontal unit is one quarter of the average character width for the dialog box’s font, and the vertical unit is one eighth of the average character height. In this way, dialog boxes adjust themselves to the screen on which they appear.

OK now start the tutorial.

       1.       Create an MFC Dialog based Program
      2.       Add following controls (as on the picture). Or any other control you want.


      3.       Add 3 private member variable to “BlogTest1Dlg.h” file as follow

private:
       CRect m_rectWindow;
       CRect m_rectButton;
       bool m_bResized = false;
      4.       Now double click on Resize & Make Topmost button and add the following code.

void CBlogTest1Dlg::OnBnClickedButton1()
{
   if(!m_bResized)
   {
      // Get Windows Rectangle: x, y, cx, cy
      GetWindowRect(&m_rectWindow); 
      // Get Buttons Rectangle: x, y, cx, cy
      GetDlgItem(IDC_BUTTON1)->GetWindowRect(&m_rectButton);  
      SetWindowPos(&CWnd::wndTopMost, // it can be NULL as well.
                     /*int x*/m_rectWindow.left,
                     /*int y*/m_rectWindow.top,
                     /*int cx*/m_rectButton.right -                        m_rectWindow.left +(m_rectButton.left -
                       m_rectWindow.left),
                     /*int cy*/m_rectButton.bottom -
                       m_rectWindow.top + (m_rectButton.left -
                       m_rectWindow.left),
                       SWP_NOMOVE | SWP_FRAMECHANGED);
       // change the boolean value to true for the next click to
       // change back the window normal position.
         m_bResized = true;
       }
       else
       {
          SetWindowPos(&CWnd::wndNoTopMost, m_rectWindow.left,
             m_rectWindow.top, m_rectWindow.right-m_rectWindow.left,
             m_rectWindow.bottom - m_rectWindow.top, 
             SWP_NOMOVE|SWP_FRAMECHANGED);
          SendMessage(DM_REPOSITION, 0, 0);
          // change the boolean value to false for the next click to
          // change window to compact position.
          m_bResized = false;
       }
}

 

5.       Now press F5 and Run the program.

When you click the Button “Resize & Make Topmost” It will change the window like below.



Set the window on its original size as the button clicked again.
 

Tuesday, November 11, 2014

Getting Started

1. Problem Solving

Programs often are written in response to some problem or task to be solved. Let's look at an example. A bookstore enters into a file the title and publisher of each book it sells. The information is entered in the order the books are sold. Every two weeks the owner by hand computes the number of copies of each title sold and the number sold from each publisher. The list is alphabetized by publisher and used for purposes of reordering. You have been asked to supply a program to do this work.
One method of solving a big problem is to break it down into a number of smaller problems. Hopefully, these smaller problems are easier to solve. Our bookstore problem divides nicely into four sub-problems, or tasks:
1.1 Read in the sales file.
1.2 Count the sales by title and by publisher.
1.3 Sort the titles by publisher.
1.4 Write out the results.

Items 1.1, 1.2 and 1.4 represent problems we know how to solve; they do not need to be broken down further. Item 1.3, however, is still a little more than we know how to do. So we reapply our method to this item:
1.3.1 Sort the sales by publisher.
1.3.2 Within each publisher, sort the sales by title.
1.3.3 Compare adjacent title within each publisher group. For each matching pair, increment an occurrence count of the first and delete the second.

Items 1.3.1, 1.3.2 and 1.3.3 also now represent problems that we know how to solve. Since we can solve all the sub-problems that we have generated, we have in effect solved the original, bigger problem, Moreover, we see that the original order of tasks was incorrect. The sequence of actions required following:

a. Read in the sales file.
b. Sort the sales file -- first, by publisher, then, by title within publisher.
c. Compact duplicate titles.
d. Write out the results into a new file.

The resulting sequence of actions is referred to as an algorithm. The next step is to translate our algorithm into a particular programming language in this case, C++.

2. The C++ Program
In C++, an action is referred to as an expression. An expression terminated by a semicolon is referred to as a statement. The smallest independent until in a C++ Program is a statement. In natural language, an analogous construct ix the sentence. The following, for example, are statements in C++;

         int value;
      value = 7 + 1;
      cout << value;

The first statement is referred to as a declaration statement. It defines an area of computer memory associated with the name value that can integer values. The second statement is referred to as an assignment statement. It places in the area of computer memory associated with the value the result of adding 7 and 1. The third statement is an output statement. cout is the output destination associated with the user's terminal. << is the output operator. The statement writes to cout -- that is, the user's terminal, the value stored in the area of computer memory associated with the name value.

Statements are logically grouped into named units referred to as functions. For example, all the statements necessary to read in the sales file are organized into a function called readIn(). Similarly, we organize sort(), compact() and print() function.

In C++ , every program must contain a function called main(), supplied by the programmer, before the program can be run. Here is how main might be defined for the preceding algorithm:

int main()
{
    readIn();
    sort();
    compact();
    print();
    return 0;
}

A C++ program begins execution with the first statement of main(). In this case, the program begins by executing the function readIn(). Program execution continues by sequentially executing the statements within main(). A program terminates normally following execution of the last statement of main().

A function consists of four parts: a return type, the function name, an argument list, and the function body. The first three parts are collectively referred to as the function prototype. The argument list, enclosed within parentheses, contains a comma-separated list of zero or more arguments. The function body is enclosed within a pair of braces ("{}"). It consists of a sequence of program statements.

In this instance, the body of main() calls for execution the functions readIn(), sort(), compart() and print(). When these have completed, the statement return 0; is executed. return, a predefined C++ statement provides a method of terminating the execution of a function. When supplied with a value such as 0, that value becomes the return value of the function. In this case, a return value of 0 indicates the successful completion of main().

Let's turn now to how the program is made ready for execution. First we must provide definitions of readIn(), sort(), compact(), and print(). At this point, the following dummy instance are good enough.

    void readIn() { cout << "readIn()\n";}
    void sort() { cout << "sort()"\n";}
    void compact() { cout << "compact()"\n;}
    void print() { cout << "print()"\n";}

void is used to specify a function that does not provide a return value. As defined, each function will simply announce its presence on the user's terminal when invoked by main(). Later, we can replace these dummy instance with the actual functions as they are implemented. This sort of incremental method of building programs provides a useful measure of control over the programming errors we inevitably make. Trying to get a program to work all at once is simply too complicated and confusing.

I will continue on my next blog soon....


 

Monday, November 10, 2014

The Basic of C++

Hello!
First of all let me tell you my English is very poor, and I have never write a blog or article. Hope you will realize my mistakes and forgive me for my poor English.

This is the first time I write a blog. Never before I have done so. Lots of people out there may want to learn programming language. This blog is for those who want to start programming and very new. I have a little knowledge about C++ Programming and want to share it with you. Hope you will find some info will help you.

History of C++
The C++ programming language was developed at AT&T Bell Laboratories in the early 1980s by Bjarne stroustrup. It is an evolution of the C Programming language, which extends C in three important ways:
  1. It provides support for creating and using data abstractions.
  2. It provides support for object-oriented design and programming.
  3. It provides various nice improvements over existing C constructs.
 All while retaining C's simplicity of expression and speed of execution.
C++ is already widely available and is in wide use for real application and systems development. Within six months of its initial release from AT&T in late 1985, there were commercial ports of C++ available on over 24 systems, ranging from PCs to large mainframes. Since then, more ports have been made, and C++ is now available directly from many computer vendors. In 1988 the first native compilers were produced for the PC and workstation markets. Additionally, large-scale libraries and program support environments have begun to appear. The maturation of the C++ language is attested to by two recent events: the formation of an ANSI C++ committee and the publication of The Annotated  C++ Reference manual by Ellis and Stroustrup, which serves as the baseline document for the C++ ANSI committee. Papers documenting user experience with C++ have appeared in various conferences (there are now two annual conferences devoted exclusively to C++) and technical publications.

The future of C++
The language is still undergoing some small changes-- these will likely continue until the ANSI C++ committee completes its work. Our growing experience with templates, for example, has suggested some potential changes to the definition of the facility. Will they all be adopted as currently proposed? It won't be clear for a while yet. The ANSI C++ committee, however, in my opinion is doing a good job and we can be sure what changes are introduced will be well considered.

 Are there likely to be any further extensions? One that seems more likely than not is the idea of metaclasses. Metaclassed permit an object to be queried at run time about such things as it actual type. Object oriented database system feel that absence of a language-supported metaclass facility most strongly. A number of designs have been independently proposed, but nothing, as of this writing, has formally been submitted to the language extension subgroup of the ANSI C++ committee, headed y stroustrup.

For the individual first learning C++, Two question naturally arise:
  1. What is the C++ Program, anyway? How is one written?
  2. Once it is written, how do you get the program to run?
I will continue on my next blog soon.