Quantcast
Channel: CodeGuru Forums - Visual C++ Programming
Viewing all 3021 articles
Browse latest View live

Creating a virtual mini server

$
0
0
Is it possible to create a virtual mini server (like IIS) that takes http request? I have a toolbar that queries an DLL using http request, and then that DLL stores some arguments in some XML file, which is read by an anti-malware.

Now every customer can't have an IIS server installed. Most of the end users uses Windows XP home edition. So is there a way i can create a virtual mini server that can be used in these PCs for placing http request?

Noob needs easy help with command line interface

$
0
0
Hi,

I am a total idiot when it comes to command line interfaces. Unfortunately I was too young to use the family apple 2c before it was replaced by a windows computer :-(

Here is my problem. I have a programming assignment (I just need help using command line). It contains main.cpp, person.cpp, and person.h. Main.cpp needs to take and int argc and a char argv (the main declaration is below). Using visual c++'s command line, I am able to change directories so that I am at the correct directory (in this case it is C:\Users\-----\Documents\Visual Studio 2010\Projects\assignment 7 marketing\assignment 7 marketing\main.cpp). I have been able to navigate to C:\Users\------\Documents\Visual Studio 2010\Projects\assignment 7 marketing\assignment 7 marketing, but now what? How do I tell the command line interface to open the project, or compile it, or whatever I need to do to see how this program works? How do I pass it the correct arguments? If someone could please give me a step by step list of what commands I need to input that would be totally helpful. Thanks ahead of time.
Code:

int main(int argc, char* argv[])

Best way to allocate large memory

$
0
0
In my Visual C++ app, I know the total objects(CMyObject) to be allocated is 16728064 and each object is 64 byte, so the total memory to be allocated is 1GB. The memory will be allocated in the beginning, used in the whole lifetime of the app, and release in the end.

In such a case, what is the best way to allocate the memory?

Current I try to allocate the memory at the beginning, as follows:

CMyObject *p = new CMyObject[16728064];

// Perform tasks.

delete [] p;

But the allocation will fail for most of the time. Now I want to do as follows:

CMyObject *p[10];

p[0] = new CMyObject[1672806];

p[1] = new CMyObject[1672806];

…

// Perform tasks

Delete [] p[0];

….

This seems to work for some time.

Therefore, should I split the allocation into pieces as small as possible? Or are there any good solutions for such a situation?

Thanks

Problem with CListCtrl - Visual Studio 2010

$
0
0
I have a list box control inserted in a dialog application.

But I can't seem to do anything with it. I can insert items and I can't insert columns.

I don't understand. Why is that none of the documented member functions of CListCtrl do anything to effect my actual control?

Code:

BOOL CImageDialog::OnInitDialog()
{
        SetHeaderImage(m_rIniFile.getKeyValue("HeaderImage", "SavedFieldValues"));
        SetNavImg1(m_rIniFile.getKeyValue("NavImage1", "SavedFieldValues"));
        SetNavImg2(m_rIniFile.getKeyValue("NavImage2", "SavedFieldValues"));

        CListCtrl* pListCtrl = (CListCtrl*)GetDlgItem(IDC_LIST_OTHER_IMG_FILES);
        ASSERT_VALID(pListCtrl);
        pListCtrl->InsertColumn(0, "Image file");
        pListCtrl->SetColumnWidth(0, LVSCW_AUTOSIZE);

        return CMyDialog::OnInitDialog();
}

Code:

void CImageDialog::DDX_List(CDataExchange* pDX, UINT uListCtrlID, CStringArray& rarrayOtherImgFiles)
{
        CListCtrl* pListCtrl = (CListCtrl*)GetDlgItem(uListCtrlID);
        int nI = 0;
        CString strItem;

        ASSERT_VALID(pListCtrl);

        if (pDX->m_bSaveAndValidate)
        {
                m_arrayOtherImageFiles.RemoveAll();
                for (nI = 0; nI < pListCtrl->GetItemCount(); nI++)
                {
                        strItem = pListCtrl->GetItemText(nI, 1);
                        m_arrayOtherImageFiles.Add(strItem);
                }
        }
        else
        {
                pListCtrl->DeleteAllItems();
                for (nI = m_arrayOtherImageFiles.GetCount() - 1; nI >= 0; nI--)
                {
                        pListCtrl->InsertItem(0, m_arrayOtherImageFiles.GetAt(nI));
                }
        }
}
       
void CImageDialog::DoDataExchange(CDataExchange* pDX)
{
        CMyDialog::DoDataExchange(pDX);
        DDX_Text(pDX, IDC_EDIT_HEADER_IMG, m_strHeaderImageFile);
        DDX_Text(pDX, IDC_EDIT_NAV_IMG1, m_strNavImg1File);
        DDX_Text(pDX, IDC_EDIT_NAV_IMG2, m_strNavImg2File);
        DDX_Text(pDX, IDC_EDIT_OTHER_IMG_FILES, m_strOtherImgFiles);
        DDX_List(pDX, IDC_LIST_OTHER_IMG_FILES, m_arrayOtherImageFiles);
}

Problem in Displaying Bit Values

$
0
0
I am writing a program to display values from a data file as an image. But I can only get a blue screen. Here is a small program resembling my code. Could you see what I have missed? I only changed OnDraw function.

Code:

void CColorDisplayView::OnDraw(CDC* pDC)
{
        CColorDisplayDoc* pDoc = GetDocument();
        ASSERT_VALID(pDoc);
        if (!pDoc)
                return;

        CRect rect;
        GetClientRect(rect);
        int nWidth = rect.Width();
        int nHeight = rect.Height();

        // Allocate a bitmap header. Windows takes care of freeing this memory.
        BITMAPINFO *    pbmiDIB = NULL;
        pbmiDIB = (BITMAPINFO *) new BYTE[sizeof(BITMAPINFOHEADER) + 256*sizeof(WORD)];
        if (pbmiDIB == NULL)
        {
                throw;
        }

        // Fill in the BITMAPINFOHEADER
        pbmiDIB->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
        pbmiDIB->bmiHeader.biWidth = nWidth;
        pbmiDIB->bmiHeader.biHeight = nHeight;
        pbmiDIB->bmiHeader.biPlanes = 1;
        pbmiDIB->bmiHeader.biBitCount = 8;          // max 256 colors supported
        pbmiDIB->bmiHeader.biCompression = BI_RGB;
        pbmiDIB->bmiHeader.biSizeImage = 0;
        pbmiDIB->bmiHeader.biXPelsPerMeter = 0;
        pbmiDIB->bmiHeader.biYPelsPerMeter = 0;
        pbmiDIB->bmiHeader.biClrUsed = 0;
        pbmiDIB->bmiHeader.biClrImportant = 0;

        CPalette cPalette;
        BOOL success = cPalette.CreateHalftonePalette(pDC);

        CPalette* pOldPal = pDC->SelectPalette(&cPalette, FALSE);
        pDC->RealizePalette();

        // Create our DIB. This call allocates the memory for our bitmap.
        LPVOID pvBits = NULL;
        HBITMAP hBitmap = CreateDIBSection(
                pDC->GetSafeHdc(),
                pbmiDIB,
                DIB_PAL_COLORS,
                (void **)&pvBits,        // Here's where we put the image
                NULL,
                0);

        LPBYTE pSensorValues = (LPBYTE) pvBits;
        delete pbmiDIB;
        pbmiDIB = NULL;

        int k = 0;
        for(int j = 0; j < nHeight; j++) {
                for(int i = 0; i < nWidth; i++) {
                        *pSensorValues = k % 256;
                        pSensorValues++;
                }
                k++;
        }

        CDC memdc;
        memdc.CreateCompatibleDC(pDC);
        CBitmap* pOldBm = (CBitmap *) memdc.SelectObject(hBitmap);


        BOOL bRet = pDC->BitBlt(
                rect.left,
                rect.top,
                nWidth, nHeight,
                &memdc, 0, 0, SRCCOPY );
}

MFC button with icon or image

$
0
0
Can some one tell me the EASIEST way to create a button with an image on it.

I am not interested in using the owner draw property with CBitmapButton and then have to create a whole lot of bitmaps for all the different button states.

There must be a way to simply create an ordinary button which displays an image rather than or as well as a caption.....SURELY?

change menu bar font size

$
0
0
Can you change the menu bar font size in CMainFrame::OnCreate()? Here's what I have:

Code:


int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{   
 
    CRect rect;
    GetClientRect(&rect);
    if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
    {
        return -1;
    }
   
        if (!m_wndToolBar.Create(this))
        {
                TRACE0("Failed to create toolbar\n");
                return -1;      // fail to create
        }
        m_font.CreatePointFont(165, "Arial");
        m_wndToolBar.SetFont(&m_font);
    if (!m_wndStatusBar.Create(this) ||
        !m_wndStatusBar.SetIndicators(indicators,
        sizeof(indicators)/sizeof(UINT)))
    {
        TRACE0("Failed to create status bar\n");
        return -1;
    }

   
   
   
    return 0;
}

The line "m_wndToolBar.SetFont(&m_font);" does nothing. I found article on code guru http://www.codeguru.com/cpp/controls...ep-by-Step.htm. I will probably just use this if I can't make this work. But just wanted to ask. Thanks!!

How to get rid of 'not responding' message

$
0
0
I have a simple dialog based app that performs some time consuming file manipulations. The activating method contains the customary
Code:

CWaitCursor wait;
The hour glass initially appears, than after a few seconds, the dialog title bar indicates 'not responding'.

This is misleading to users as it suggests the application has ceased to function when, in fact, it's working just fine. I would like very much
to eliminate this 'not responding' message but havn't a clue how to do it. Have any of you dealt with this problem, if so, how?

Thanks.

CBitmap::LoadBitmap(...) doesn't work

$
0
0
http://msdn.microsoft.com/en-us/library/wc99t364.aspx

There must be critical info that is missing in here because simply creating a CBitmap variable and then calling LoadBitmap(....) is not working.

Can some one explain to me step by step how you load a bitmap from a PNG file with a resource ID of IDB_PNG_HELP - it is a .png file imported into resource editor (res/Help.png)

Why is CreateDIBSection() Failing in My Code?

$
0
0
Hello, below is a block of my code. I don't understand why CreateDIBSection() returns NULL. Thanks a lot in advance.
Code:

pPackedDib = (BITMAPINFO *)(malloc (sizeof(BITMAPINFOHEADER) + 256*sizeof(WORD)));
pPackedDib->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pPackedDib->bmiHeader.biWidth = 300;
pPackedDib->bmiHeader.biHeight = 450;
pPackedDib->bmiHeader.biPlanes = 1;
pPackedDib->bmiHeader.biBitCount = 8;          // max 256 colors supported
pPackedDib->bmiHeader.biCompression = BI_RGB;
pPackedDib->bmiHeader.biSizeImage = 0;
pPackedDib->bmiHeader.biXPelsPerMeter = 0;
pPackedDib->bmiHeader.biYPelsPerMeter = 0;
pPackedDib->bmiHeader.biClrUsed = 0;
pPackedDib->bmiHeader.biClrImportant = 0;
pPackedDib->bmiColors[0].rgbRed = 204;
pPackedDib->bmiColors[0].rgbGreen = 204;
pPackedDib->bmiColors[0].rgbBlue = 204;
pPackedDib->bmiColors[0].rgbReserved = 0;

if (pPackedDib)
    {
    // Create the DIB section from the DIB
        hBitmap = CreateDIBSection (NULL,
                                              pPackedDib,
                                              DIB_PAL_COLORS,
                                              &pBits,
                                              NULL, 0);
        ...

        free(pPackedDib);
    }

IDropTarget + elevated process. Msgs for ChangeWindowMessageFilter to make it work?

$
0
0
I'm using the following approach to register an individual control in my MFC/C++ application for a drag-and-drop operation:

Code:

//I have my own class derived from IDropTarget
class CDropTargetSpec :
    public IDropTarget
{
    //IUnknown implementation
    HRESULT __stdcall QueryInterface (REFIID iid, void** ppvObject);
    ULONG  __stdcall AddRef (void);
    ULONG  __stdcall Release (void);

    //IDropTarget implementation
    HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect);
    HRESULT __stdcall DragOver (DWORD grfKeyState, POINTL pt, DWORD * pdwEffect);
    HRESULT __stdcall DragLeave (void);
    HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect);

    //...
};

Then to register it I do:

Code:

//Error checks are omitted for brevity
CDropTargetSpec *pDropTarget = new CDropTargetSpec();
CoLockObjectExternal(pDropTarget, TRUE, FALSE);
RegisterDragDrop(hDragRecepientWnd, pDropTarget));

The drag and drop itself is processed by the CDropTargetSpec class methods.

This approach works fine, except when my app runs elevated. In that case the registration methods succeed, but when I try to drag and drop files into my window, none of the methods from CDropTargetSpec class get called and the mouse shows "Not Available" cursor.

I know that Microsoft added that UIPI thing which prevents messages from lower processes to be dispatched into elevated processes. They also added the ChangeWindowMessageFilter API to bypass it, but I can't seem to figure out what messages I need to allow for my drag-and-drop to work.

I keep finding the following code sequence that I need to call from the WM_INITDIALOG method for my app:

Code:

ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD);
ChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD);
ChangeWindowMessageFilter(WM_COPYGLOBALDATA, MSGFLT_ADD);  //0x0049

but even though it works for a simple drag-and-drop into the app itself, my method above for the IDropTarget doesn't seem to work.

So any ideas what am I missing here?

ImageList question

$
0
0
Hi, ALL,
An ImageList_Create() function (see here) takes 2 parameters: cx and cy which are the width and height of each image.

Everything is good if I know in advance what size my images will have. But what if I don't?

Let's say I select 32x32 and my images are sized as 16x16. What will happen with the image list? Or my images are 48x48 and the image list should grow to accomodate the extra space. Since on Windows image list is just one big bitmap, will the height of the image list shrink/grow to 16/48 or not? Is there a way to test such behavior?

The problem I'm having is to check whether the actual images will be truncated when they are bigger that the image list initial size or not or whether I will see some extra space if the images are smaller.

The closest way I see is this function, but I am not sure its the right one to apply to the image list itself and not to the image inside the list.

Does anybody know how to test this properly and reliably on Windows XP+?

Thank you.

Moving from VC++ 6.0 to VC++.NET

$
0
0
I have, what to me, looks like a large project. Originally written about 90% in VB6 and the remainder in VC++ (Visual C++ 6.0 Enterprise Edition). There are maybe 2,000 lines of code written in VC++ which constitute a DLL with about 80 functions (81 to be precise)

There are two reasons I have used VC++. The first is that speed is of the essence - the program may literally run for weeks finding solutions and the speed of the central loop is crucial. From experience it seems like the routines in VC++ run about three times quicker than the equivalent written in VB6

Secondly, I have written a lot of bit handing routines using inline ASM.

I have spent several months converting the VB6 stuff into vb.net (which run at about half the speed of VB6) and am now looking at the VC++ stuff

Some questions:

1. Is VC++.net going to run at the same speed as vb.net as I understand they both translate into an Intermediate language? If so, it will be a LOT slower than VC++ 6.0?

2. Can I use inline ASM in VC+.net?

3. Can I view (somehow) the disassembled code as I can in VC++? This is very handy when you are trying to optimise speed

4. What version of VC++.net should I use (I am currently using VB 2010 but am happy to spend money and upgrade if necessary)

5. Any general observations from people who have already experienced this transition will be very much appreciated

Many thanks!

Compile 64bit more like 32bit in vs2008? issue with CxImage Library.

$
0
0
I have an issue with CxImage 7.01 library in 64bit mode with a certain TIFF file with Jpeg compression causing a crash.

BUT compiled as 32bit it works fine! but I need it as 64bit for a called dll been called by a 64bit app.

So, is there any flags that can be unset in the compiler to compile more like 32bit mode?

The issue is described below runnin the demo app provided:-
Windows 7, 64bit. Visual Studio 2008 sp

Unhandled exception at 0x00000001401d726a in demod.exe: 0xC0000005: Access violation writing location 0x0000000405c6ab30.


tif_getimage.c

/*
* 8-bit packed YCbCr samples w/ 2,2 subsampling => RGB
*/

DECLAREContigPutFunc(putcontig8bitYCbCr22tile)
{
uint32* cp2;
(void) y;
fromskew = (fromskew / 2) * 6;
cp2 = cp+w+toskew;
while (h>=2) {
x = w;
while (x>=2) {
uint32 Cb = pp[4];
uint32 Cr = pp[5];
YCbCrtoRGB(cp[0], pp[0]); <--- ERRORS OUT HERE!

Worker Thread handle leak

$
0
0
I my application a Worker Thread is started every 5 seconds. After a while (about 2 hours) no further threads are beeing started. Checking the application with Microsoft Process Explorer showed, that with every starting thread a handle is generated but not closed properly when the threads return. This also happens when the function does nothing but returning the value 0 or any other number value.

Regulary all handles are automatically closed when a thread is terminated. The output also shows that the WinThread has been ended with return value 0. In this case the handles seem to remain. How can I close them?

Every code is within the same class.

thread function declaration:
Code:

static UINT SendGPSData( LPVOID pParam);

or (with no effect):

static UINT __cdecl SendGPSData( LPVOID pParam);

thread function definition:
Code:

UINT CMyDlg::SendGPSData( LPVOID pParam)
{               
        return 0;
}

the call triggered by Timer:
Code:

AfxBeginThread( &CMyDlg::SendGPSData, (LPVOID)structure);

Problem with CFileFind

$
0
0
A fairly simple loop:

Code:

        if (rFinder.FindFile(strFolder + "\\*.*"))
        {
                while (rFinder.FindNextFile())
                {
                        strPath = rFinder.GetFilePath();
.
.
.
.
              }
        }

What on earth would be causing this to only find directories - no files what so ever?

I also noticed that, in another test directory I was using, CFileFind failed to find this sub-directory directory: "HTML Codes - Table of ascii characters and symbols_files". It did find the single HTML file that was also in this directory however.

This class seems to be some what unreliable.

Perhaps I would be better off using the old fashioned C version: findfirst and findnext.

How do I create Visual C++ apps?

$
0
0
How do I create Visual C++ applications that only rely on having Visual C++ redistributable installed and NOT .NET framework?

I have Visual Studio 2005/2008/2012 express editions only. Can I compile C++ codes to do this in the express versions?

Creating a Grid?

$
0
0
Hi guys, I am working on another assignment and was wondering if anyone could help me by showing me a basic layout in how to complete it. I am pretty confused. Here it is:

A Program

For this program, you are to design a class for representing a rectangular grid and use it to allow a user to query a grid interactively as part of a game.

Background:

Pegboard problems are single-player games played on a grid (or pegboard), in which moves are made by successively jumping and removing pegs from the pegboard. A peg can jump an adjacent peg if there is a slot adjacent to that peg in the opposite direction - horizontally, vertically, or diagonally. After a peg has been jumped, it is removed from the board (and possibly eaten). A typical objective of this problem is to begin with a full pegboard from which one peg has been removed, and determine a sequence of jumps which will result in one peg remaining, perhaps in the position from which the first peg was removed. A popular form of this problem involves a rectangular pegboard with 4 slots on a side (see below), which proves to be a challenging problem for a human being.

For instance, consider the example below, which demonstrates the first few moves of a session:

Pegboard Example
0 1 2 3
+---------+
0 | X X X X |
1 | X X X X |
2 | X X X X |
3 | X X X X |
+---------+

Which peg should be
removed to start? 3 1

Pegboard Example
0 1 2 3
+---------+
0 | X X X X |
1 | X X X X |
2 | X X X X |
3 | X O X X |
+---------+

Enter move: 1 3 3 1


Pegboard Example
0 1 2 3
+---------+
0 | X X X X |
1 | X X X O |
2 | X X O X |
3 | X X X X |
+---------+

Enter move: 2 0 2 2


Pegboard Example
0 1 2 3
+---------+
0 | X X X X |
1 | X X X O |
2 | O O X X |
3 | X X X X |
+---------+

Enter move: 1 1 1 3


A move can be characterized by the attributes (startPos, endPos), which respectively refer to the position of a peg that is about to jump (jumper) and the new position of the jumper. The position of the peg that is jumped and removed can be determined by averaging the respective row and column positions of startPos and endPos, provided those positions describe a legal move.

For instance, in the last panel of the example depicted above, the peg in position startPos=(3,3)can jump over the peg in position (2,3)and land in position endPos=(1,3). The "middle position" of the peg that gets jumped over can be found by averaging the coordinate values of startPos and endPos, i.e, ((1+3)/2,(3+3)/2) = (2,3).



The Assignment:

You will design and implement a class called Grid that represents a pegboard as described above. The underlying main data object in a Grid is a vector of vectors!!! Each row is itself a vector, where each element contains a value that designates either a full or empty cell. A Grid also knows how many rows and how many columns it has, and allows direct access to its grid elements via the [] operator -- that is, the element in row i, column j may be referred to as G[i][j]. A Grid also has an overloaded output operator so that it may be displayed on a console or saved in a file.

Your program should provide instructions for the user, print a copy of the board at each step, and allow the user to indicate the row and column numbers of the start position and end position for the next move. If the move is legal, the pegboard should be updated accordingly; otherwise the user should be prompted to enter a valid move. The user should also be permitted to quit at any time (especially when the game is over!)

Thank you for any help!

Calling a DLL written in VC++.NET Native Code from a VB.NET project

$
0
0
I have just installed VC++.net (2010 Express version) on a Win XP machine (the reason I am still using XP is that I need to use VB6 for a while and it will not install on Win 7/8). I would install 2013 VC++.net but it is only available for Win 7/8

So, i have built a small test dll and am trying to call it from a project written in vb.net, as follows:

In VC++
Code:

extern "C" {
        __declspec(dllexport) double TestF();
}

__declspec(dllexport) double TestF(){
 
  double ax = 0;
  ax = 999;
  return ax;
}

In vb.net
Code:

Public Declare Function TestF Lib "C:\....\mopeks.dll" () As Double

  dblX = TestF()

This works and it returns "999" as hoped for. The problem is that when I include a parameter so that we have:

__declspec(dllexport) double TestF(double dblValue){ etc etc

I get PInvoke problems, namely:

"PInvokeStackImbalance was detected
Message: A call to PInvoke function 'MOPEKS!MOPEKS.prjDLLs::TestF' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature."

I suspect I need to use "_stdcall" or whatever? Any guidance much appreciated

CRichEditCtrl paragraph formatting and justification

$
0
0
I am using CRichEditCtrl in a dialog. I want to have auto wrapping off and paragraph justification as center or right.
To turn off auto wrap i used SetTargetDevice which worked fine but the justification changed to left automatically.
I tried to use SetParaFormat after setting the SetTargetDevice but unable to make the justification center or right when auto wrap is off.
Has anybody tried this before?
Viewing all 3021 articles
Browse latest View live