EzDevInfo.com

mfc interview questions

Top mfc frequently asked interview questions

Where is a good place to start programming GUIs for windows?

I have experience writing console and network client/server applications in C and C++, but I know next to nothing about using the win32 visual API, MFC, Qt, wxWidgets, etc. Where is a good place to start, and what method should I specialize in, so as to be future ready and robust?


Source: (StackOverflow)

LPCSTR, LPCTSTR and LPTSTR

What the difference between LPCSTR, LPCTSTR and LPTSTR?

Why do we need to do this to convert a string into a LV / _ITEM structure variable pszText:

LV_DISPINFO dispinfo;  
dispinfo.item.pszText = LPTSTR((LPCTSTR)string);

Source: (StackOverflow)

Advertisements

How to detect a CListCtrl selection change?

I want to execute some code when the user selects a row in a CListCtrl (report view, I don't care about the other viewing modes).

How do I catch this event? is there some message I can map or a method like "OnSelectionChanged" or something like that?


Source: (StackOverflow)

What's with the "Afx" in StdAfx.h?

I'm just curious what Afx stands for. And what about Fx in FxCop?


Source: (StackOverflow)

Private and Protected Members : C++

Can someone enlighten me as to the difference between private and protected members in classes? I understand from best practice conventions that variables and functions which are not called outside the class should be made private - but looking at my MFC project, MFC seems to favour protected.

Whats the difference and which should I use?

Thanks.


Source: (StackOverflow)

What's the fundamental difference between MFC and ATL?

tl;dr:

Assuming I am only using them for "normal" GUI programs (no COM, no ActiveX, nothing fancy), what is the fundamental difference I will see between ATL and MFC, to help me figure out which one to use?


I've done some searches on the web, but ultimately none of the answers really answered my question:

  • http://msdn.microsoft.com/en-us/library/bk8ytxz5(v=vs.80).aspx:

    • "ATL is a fast, easy way to both create a COM component in C++ and maintain a small footprint. Use ATL to create a control if you don't need all of the built-in functionality that MFC automatically provides."

      Doesn't really answer my question, because:

      • I'm not working with COM.

      • Does this imply MFC isn't fast? Why/how?

    • "MFC allows you to create full applications, ActiveX controls, and active documents. If you have already created a control with MFC, you may want to continue development in MFC. When creating a new control, consider using ATL if you don't need all of MFC's built-in functionality."

      Also doesn't answer my question, because:

      • I don't really even know what ActiveX is in the first place.

      • It looks as though Microsoft is discouraging the use of MFC, but I can't figure out why.

      • What exactly is MFC's "built-in functionality" that ATL doesn't provide?

    • In general, this doesn't answer my question because it doesn't explain the downsides and the reasons behind them.

because directly or indirectly, everything seems to link back to the previous page:

What I have currently observed (within the last couple of days, while trying to learn both):

  • ATL is based on templates, or compile-time polymorphism.
    • ATL methods tend to be non-virtual, and tend to return references.
  • MFC is based on virtual methods, or run-time polymorphism.
    • MFC methods tend to be virtual, and tend to return pointers.

But there doesn't seem to be any architectural difference between them:

  • Both use message maps (BEGIN_MSG_MAP vs. BEGIN_MESSAGE_MAP... big deal)
  • Both wrap Win32 methods into classes
  • Both seem to have similar classes CWnd vs. CWindow

But then, if there's no real difference except for the compile-time vs. run-time aspect, then why do both of them exist? Shouldn't one of them be enough?

What am I missing here?


Source: (StackOverflow)

How to convert CString and ::std::string ::std::wstring to each other?

CString is quite handy, while std::string is more compatible with STL container. I am using hash_map. However, hash_map does not support CString as key, so I want to convert CString into std::string.

Writing a CString hash function seems to take a lot of time.

CString -----> std::string

How can I do this?

std::string -----> CString:

inline CString toCString(std::string const& str)
{
    return CString(str.c_str()); 
}

Am I right?


EDIT:

Here are more questions:

How can I convert wstring, CString to each other?

//wstring -> CString,
std::wstring src;
CString result(src.c_str());
//CString->wstring. 
CString src;
::std::wstring des(src.GetString());

Is there any problem?

How can I convert std::wstring, std::string to each other?


Source: (StackOverflow)

How do I decide whether to use ATL, MFC, Win32 or CLR for a new C++ project?

I'm just starting my first C++ project. I'm using Visual Studio 2008. It's a single-form Windows application that accesses a couple of databases and initiates a WebSphere MQ transaction. I basically understand the differences among ATL, MFC, Win32 (I'm a little hazy on that one actually) and CLR, but I'm at a loss as to how I should choose.

Is one or more of these just there for backward-compatibility?

Is CLR a bad idea?

Any suggestions appreciated.

Edit: I've chosen C++ for this project for reasons I didn't go into in the post, which are not entirely technical. So, assuming C++ is the only/best option, which should I choose?


Source: (StackOverflow)

App does not run with VS 2008 SP1 DLLs, previous version works with RTM versions

Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system.

Pre-SP1, this was working fine (and still works fine on our developer machines). Now that we've done some testing post-SP1 I've been pulling my hair out since yesterday morning.

First off, our NSIS installer script pulls the dlls and manifest files from the redist folder. These were no longer correct, as the app still links to the RTM version.

So I added the define for _BIND_TO_CURRENT_VCLIBS_VERSION=1 to all of our projects so that they will use the SP1 DLLs in the redist folder (or subsequent ones as new service packs come out). It took me hours to find this.

I've double checked the generated manifest files in the intermediate files folder from the compilation, and they correctly list the 9.0.30729.1 SP1 versions. I've double and triple checked depends on a clean machine: it all links to the local dlls with no errors.

Running the app still gets the following error:

The application failed to initialize properly (0xc0150002). Click on OK to terminate the application.

None of the searches I've done on google or microsoft have come up with anything that relates to my specific issues (but there are hits back to 2005 with this error message).

Any one had any similar problem with SP1?

Options:

  • Find the problem and fix it so it works as it should (preferred)
  • Install the redist
  • dig out the old RTM dlls and manifest files and remove the #define to use the current ones. (I've got them in an earlier installer build, since Microsoft blasts them out of your redist folder!)

Edit: I've tried re-building with the define turned off (link to RTM dlls), and that works as long as the RTM dlls are installed in the folder. If the SP1 dlls are dropped in, it gets the following error:

c:\Program Files\...\...\X.exe

This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.

Has no-one else had to deal with this issue?

Edit: Just for grins, I downloaded and ran the vcredist_x86.exe for VS2008SP1 on my test machine. It works. With the SP1 DLLs. And my RTM linked app. But NOT in a private side-by-side distribution that worked pre-SP1.


Source: (StackOverflow)

C++ MFC vs .NET?

My colleagues are using Visual Studio 2002 and uses the C++ MFC. I am developing in C #.

It has not been any problems before, but now questioning our customers if we really should develop in different environments. My colleagues think (of course) that I should move to C++ MFC. I think that they can use .NET instead of MFC.

Is there any point to learn the MFC? It feels a bit outmoded, or am I wrong? What are the arguments against and for .NET compared with MFC?

Edit:

We are developing process systems and assistance applications for the nuclear industry. The main application is an emulator that emulates an old computer system and uses C++/MFC. It is very time critical, maybe the core should it still be in native C++. But the GUI to the emulator and all surrounding applications are not particularly critical.

And is there any real reason that you should replace the existing MFC application?


Source: (StackOverflow)

Convert CString to const char*

How do I convert from CString to const char* in my Unicode MFC application?


Source: (StackOverflow)

Ever done a total rewrite of a large C++ application in C#? [closed]

I know Joel says to never do it, and I agree with this in most cases. I do think there are cases where it is justified.

We have a large C++ application (around 250,000 total lines of code) that uses a MFC front end and a Windows service as the core components. We are thinking about moving the project to C#.

The reasons we are thinking about rewriting are:

  1. Faster development time
  2. Use of WCF and other .NET built-in features
  3. More consistent operation on various systems
  4. Easier 64 bit support
  5. Many nice .NET libraries and components out there

Has anyone done a rewrite like this? Was it successful?


EDIT:

The project is almost 10 years old now, and we are getting to the point that adding new features we want would be writing significant functionality that .NET already has built-in.


Source: (StackOverflow)

Convert MFC CString to integer

How to convert a CString to integer in MFC (VC++ 6.0)


Source: (StackOverflow)

How do I force windows NOT to redraw anything in my dialog when the user is resizing my dialog?

When the user grabs a corner of a resizable window, and then moves it, windows first moves the contents of the window around, then issues a WM_SIZE to the window being resized.

Thus, in a dialog where I want to control the movement of various child controls, and I want to eliminate flickering, the user first sees what windows OS thinks the window will look like (because, AFAICT, the OS uses a bitblt approach to moving things around inside the window before sending the WM_SIZE) - and only then does my dialog get to handle moving its child controls around, or resize them, etc., after which it must force things to repaint, which now causes flicker (at the very least).

My main question is: Is there a way to force windows NOT to do this stupid bitblt thing? Its definitely going to be wrong in the case of a window with controls that move as the window is resized, or that resize themselves as their parent is resized. Either way, having the OS do a pre-paint just screws the works.

I thought for a time that it might be related to CS_HREDRAW and CSVREDRAW class flags. However, the reality is that I don't want the OS to ask me to erase the window - I just want to do the repainting myself without the OS first changing the contents of my window (i.e. I want the display to be what it was before the user started resizing - without any bitblit'ing from the OS). And I don't want the OS to tell every control that it needs to be redrawn either (unless it happened to be one that was in fact obscured or revealed by the resize.

What I really want:

  1. To move & resize child controls before anything gets updated onscreen.
  2. Draw all of the moved or resized child controls completely so that they appear without artifacts at their new size & location.
  3. Draw the spaces inbetween the child controls without impacting the child controls themselves.

NOTE: Steps 2 and 3 could be reversed.

The above three things appear to happen correctly when I use DeferSetWindowPos() in combination with the dialog resource marked as WS_CLIPCHILDREN.

I'd get an additional small benefit if I could do the above to a memory DC, and then only do a single bitblt at the end of the WM_SIZE handler.

I have played with this for a while now, and I cannot escape two things:

  1. I still am unable to suppress Windows from doing a 'predictive bitblt'. Answer: See below for a solution that overrides WM_NCCALCSIZE to disable this behavior.

  2. I cannot see how one can build a dialog where its child controls draw to a double buffer. Answer: See John's answer (marked as answer) below for how to ask Windows OS to double buffer your dialog (note: this disallows any GetDC() in-between paint operations, according to the docs).


My Final Solution (Thank you everyone who contributed, esp. John K.):

After much sweat and tears, I have found that the following technique works flawlessly, both in Aero and in XP or with Aero disabled. Flicking is non-existent(1).

  1. Hook the dialog proc.
  2. Override WM_NCCALCSIZE to force Windows to validate the entire client area, and not bitblt anything.
  3. Override WM_SIZE to do all of your moves & resizes using BeginDeferWindowPos/DeferWindowPos/EndDeferWindowPos for all visible windows.
  4. Ensure that the dialog window has the WS_CLIPCHILDREN style.
  5. Do NOT use CS_HREDRAW|CS_VREDRAW (dialogs don't, so generally not an issue).

The layout code is up to you - its easy enough to find examples on CodeGuru or CodeProject of layout managers, or to roll your own.

Here are some code excerpts that should get you most of the way:

LRESULT ResizeManager::WinProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    switch (msg)
    {
    case WM_ENTERSIZEMOVE:
        m_bResizeOrMove = true;
        break;

    case WM_NCCALCSIZE:
        // The WM_NCCALCSIZE idea was given to me by John Knoeller: 
        // see: http://stackoverflow.com/questions/2165759/how-do-i-force-windows-not-to-redraw-anything-in-my-dialog-when-the-user-is-resiz
        // 
        // The default implementation is to simply return zero (0).
        //
        // The MSDN docs indicate that this causes Windows to automatically move all of the child controls to follow the client's origin
        // and experience shows that it bitblts the window's contents before we get a WM_SIZE.
        // Hence, our child controls have been moved, everything has been painted at its new position, then we get a WM_SIZE.
        //
        // Instead, we calculate the correct client rect for our new size or position, and simply tell windows to preserve this (don't repaint it)
        // and then we execute a new layout of our child controls during the WM_SIZE handler, using DeferWindowPos to ensure that everything
        // is moved, sized, and drawn in one go, minimizing any potential flicker (it has to be drawn once, over the top at its new layout, at a minimum).
        //
        // It is important to note that we must move all controls.  We short-circuit the normal Windows logic that moves our child controls for us.
        //
        // Other notes:
        //  Simply zeroing out the source and destination client rectangles (rgrc[1] and rgrc[2]) simply causes Windows 
        //  to invalidate the entire client area, exacerbating the flicker problem.
        //
        //  If we return anything but zero (0), we absolutely must have set up rgrc[0] to be the correct client rect for the new size / location
        //  otherwise Windows sees our client rect as being equal to our proposed window rect, and from that point forward we're missing our non-client frame

        // only override this if we're handling a resize or move (I am currently unaware of how to distinguish between them)
        // though it may be adequate to test for wparam != 0, as we are
        if (bool bCalcValidRects = wparam && m_bResizeOrMove)
        {
            NCCALCSIZE_PARAMS * nccs_params = (NCCALCSIZE_PARAMS *)lparam;

            // ask the base implementation to compute the client coordinates from the window coordinates (destination rect)
            m_ResizeHook.BaseProc(hwnd, msg, FALSE, (LPARAM)&nccs_params->rgrc[0]);

            // make the source & target the same (don't bitblt anything)
            // NOTE: we need the target to be the entire new client rectangle, because we want windows to perceive it as being valid (not in need of painting)
            nccs_params->rgrc[1] = nccs_params->rgrc[2];

            // we need to ensure that we tell windows to preserve the client area we specified
            // if I read the docs correctly, then no bitblt should occur (at the very least, its a benign bitblt since it is from/to the same place)
            return WVR_ALIGNLEFT|WVR_ALIGNTOP;
        }
        break;

    case WM_SIZE:
        ASSERT(m_bResizeOrMove);
        Resize(hwnd, LOWORD(lparam), HIWORD(lparam));
        break;

    case WM_EXITSIZEMOVE:
        m_bResizeOrMove = false;
        break;
    }

    return m_ResizeHook.BaseProc(hwnd, msg, wparam, lparam);
}

The resizing is really done by the Resize() member, like so:

// execute the resizing of all controls
void ResizeManager::Resize(HWND hwnd, long cx, long cy)
{
    // defer the moves & resizes for all visible controls
    HDWP hdwp = BeginDeferWindowPos(m_resizables.size());
    ASSERT(hdwp);

    // reposition everything without doing any drawing!
    for (ResizeAgentVector::const_iterator it = m_resizables.begin(), end = m_resizables.end(); it != end; ++it)
        VERIFY(hdwp == it->Reposition(hdwp, cx, cy));

    // now, do all of the moves & resizes at once
    VERIFY(EndDeferWindowPos(hdwp));
}

And perhaps the final tricky bit can be seen in the ResizeAgent's Reposition() handler:

HDWP ResizeManager::ResizeAgent::Reposition(HDWP hdwp, long cx, long cy) const
{
    // can't very well move things that no longer exist
    if (!IsWindow(hwndControl))
        return hdwp;

    // calculate our new rect
    const long left   = IsFloatLeft()   ? cx - offset.left    : offset.left;
    const long right  = IsFloatRight()  ? cx - offset.right   : offset.right;
    const long top    = IsFloatTop()    ? cy - offset.top     : offset.top;
    const long bottom = IsFloatBottom() ? cy - offset.bottom  : offset.bottom;

    // compute height & width
    const long width = right - left;
    const long height = bottom - top;

    // we can defer it only if it is visible
    if (IsWindowVisible(hwndControl))
        return ::DeferWindowPos(hdwp, hwndControl, NULL, left, top, width, height, SWP_NOZORDER|SWP_NOACTIVATE);

    // do it immediately for an invisible window
    MoveWindow(hwndControl, left, top, width, height, FALSE);

    // indicate that the defer operation should still be valid
    return hdwp;
}

The 'tricky' being that we avoid trying to mess with any windows that have been destroyed, and we don't try to defer a SetWindowPos against a window that is not visible (as this is documented as "will fail".

I've tested the above in a real project that hides some controls, and makes use of fairly complex layouts with excellent success. There is zero flickering(1) even without Aero, even when you resize using the upper left corner of the dialog window (most resizable windows will show the most flickering and problems when you grab that handle - IE, FireFox, etc.).

If there is interest enough, I could be persuaded to edit my findings with a real example implementation for CodeProject.com or somewhere similar. Message me.

(1) Please note that it is impossible to avoid one draw over the top of whatever used to be there. For every part of the dialog that has not changed, the user can see nothing (no flicker whatsoever). But where things have changed, there is a change visible to the user - this is impossible to avoid, and is a 100% solution.


Source: (StackOverflow)

Is MFC still used for new development (with any material volume)?

I've never been a big fan of MFC, but that's not really the point. I read that Microsoft is due to release a new version of MFC in 2010 and it really struck me as odd - I thought MFC was dead (no ill intention, I really did).

Is is MFC used for new developments? If so, whats the benefit? I couldn't imagine it having any benefit over something such as C# (or even just c++ using Win32 APIs for that matter).


Source: (StackOverflow)