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

Resizing Controls and Text content

$
0
0
Hello all,

I have a SDI application that uses a CFormView class to create a window and this window has 2 buttons and 2 edit boxes.

I can resize this window, like minimize and maximize, but the controls all stay at the same place.

I know that it's possible to move the controls based on window size.

But what i want to do is, as the window is expanded the controls and it's text content to grow proportionally and same when the window is shrinked.

Is that possible to do? i.e., increase/decrease size of controls and texts per window size.

Any sample code will help.

Thanks in advance.

[RESOLVED] BitBlt issues with memory DC created from printer DC

$
0
0
i have an issue with a fix i made to allow a flood filled object be printed...

so, the full story is we were using the windows GDI FloodFill function, which we noticed doesnt work on printers, so what i found on the inet, was to create a memory DC, compatible with the printer DC, and make all my drawing operations on the memory DC, and then BitBlt it all at once to the printer DC (i had to change to use a recursive, color replacment flood fill function too, since the memory DC only allows what the main DC did)

the problem is the memory DC seems to be a pixel or two bigger on the x and y, but i dont know what to do, when i get the selected bitmap from the memory DC, it shows it to be the correct size, i would like to use StretchBlt, but the values i have access to use as params for StretchBlt, make it no different than calling BitBlt

heres my code:

Code:

HDC hMemPrnDC = CreateCompatibleDC (hPrnDC);
HBITMAP hBitmap = CreateCompatibleBitmap (hPrnDC, iWidthLP, iHeightLP);
HBITMAP hOldBitmap = SelectBitmap (hMemPrnDC, hBitmap);

    // paint the whole memory DC with the window color
HBRUSH hBrush = CreateSolidBrush (GetSysColor (COLOR_WINDOW));
RECT rect;
    // add one to right and bottom, FillRect doesnt include the right and bottom edges
SetRect (&rect, 0, 0, iWidthLP + 1, iHeightLP + 1);
    // NOTE: im doing this cause it starts out as all black
FillRect (hMemPrnDC, &rect, hBrush);

    // delete object
DeleteBrush (hBrush);

//
// do all my MoveToEx, LineTo, Ellipse, Arc, TextOut,
// SetPixel, etc calls on hMemPrnDC here
//

    // copy all the memory DC drawing data to the printer DC
BitBlt (hPrnDC, 0, 0, iWidthLP, iHeightLP, hMemPrnDC, 0, 0, SRCCOPY);

    // select old bitmap, and clean up objects
SelectBitmap (hMemPrnDC, hOldBitmap);
DeleteBitmap (hBitmap);
DeleteDC (hMemPrnDC);
hMemPrnDC = NULL;

here is a link to a PDF print where I draw straight to the printer DC: hPrnDC.pdf

and here is the same but I draw to the memory DC then BitBlt it to the printer DC: hMemPrnDC.pdf

now, I did enable my recursive flood fill function on the second, to show an example of what we are trying to achieve, it does the same without it, so that is not an issue

as you can see, the bottom and right edge are cut off, I'm also concerned about the differences in font & line weight between the two, but not as much as the sizing mismatch

NOTE: the filename printed at the top doesn't go through the memory DC, that is always drawn straight to the printer DC

let me know if you need more info...

thanks in advance!!!

Help with connecting to ms sql server 2008

$
0
0
Hi everybody,

I’m a little bit new at Visual c++, and for my work I need to make a little program(in c++ 2008) that connects to a MS SQL 2008R2 database.
So I wander if someone can tell me how I need to do that?

I hope to hear something soon.

CString class in non-MFC static library

$
0
0
Hi All,

I have a non-MFC static library which I share between a number of different projects, some non-MFC and some MFC. Currently the static library uses a typedef of std::wstring and std::string for UNICODE and non-UNICODE builds.

After discovering it's possible to use CString in non-MFC applications, by including atlstr.h header, I decided I'd rather that than using stl strings and having to keep converting between the different types. However, I seem to be struggling with linker errors when linking the library with a MFC application.

Does anyone know if this is possible? Can I create a non-MFC static library using CString from atlstr.h and link it with a MFC application?

Thanks in advance,
AnotherMuggle.

CFileDialog doesn't display the file name correctly

$
0
0
I haven't seen this before but on Windows 7 Home Professional and VC 2012 in one particular app, a CFileDialog displays only the rightmost 11 characters plus the extension of the default file name. The rest of the name is there and you can scroll left in the file name edit to display it all, but initially the text is shifted left so it doesn't all display. Hope that makes sense.

This is the code.
Code:

        CFileDialog dlg(TRUE, "csv", strFileName, OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY, "Comma Seperated Values Files (*.csv)|*.csv|All Files (*.*)|*.*||");
strFileName can contain anything and it will do it. Even a string literal will do it.

Any ideas?

Need help resizing panes

$
0
0
I need help from someone who understands the nature of CDockablePane derived windows better than I.

I have an SDI with 2 CDockablePane derived windows. I wish to have them resize with their original proportions, but cannot figure out how to do that.

Should look like the picture with relative sizes and shapes being the same regardless of resizing of the main window.

Demo app is attached.
Attached Images
 
Attached Files

Error while using cin.get

$
0
0
Hi, Line 76: cin.get(g.handicap+count);
Pre compile error dot in between cin and get. no instance of overload function ...


Code:

// golf.h -- for pe-9.cpp
const int Len = 40;
struct golf
{
        char fullname[Len];
        int handicap;
};

//non-interactive version:
//  function sets golf structure to provided name, handicap
//  using vlues passed as arguments to the function
void setgolf(golf & g, const char * name, int hc);

// interactive version:
// function name and handicap from user
// and sets the members of g to the values entered
// returns 1 if name is entered, 0 if name is empty string
int setgolf(golf & g);

// function resets handicap to new value
void handicap(golf & g, int hc);

// function displays contents of golf structure
void showgolf(const golf & g);

// chapEx9-1

#include <iostream>
#include "golf.h"
using namespace std;

int main()
{
  golf ann;
        setgolf(ann, "Ann Birdfree", 24);
        showgolf(ann);
        cout << "Enter how many golfers name and handicap do you want to enter: ";
        int ngolfers;
        cin >> ngolfers;
        while (cin.get() != '\n')
                continue;

        golf * ptr_golf = new golf[ngolfers];

        //int entered = getinfo
        int rint = 1;
        while (rint == 1)
                rint = setgolf(ptr_golf);
        showgolf(ann);
}


// golf.cpp load and show golf struc
#include<iostream>
#include "golf.h"

using namespace std;

void setgolf(golf & g, const char * name, int hc)
{
        strcpy_s(g.fullname, name);
        g.handicap = hc;
        // strlen(name)
}

int setgolf(golf & g)
{
       
        static int count = 1;
        static int pos = 0;

        char fname[40];
        cout << "Enter golfers name: ";
        cin.getline(g.fullname+count, 40, '\n');
        cout << "Enter golfers handicap: ";
        cin.get(g.handicap+count);
        cin.get();
       
        ++count;

        if (strlen(g.fullname) == 0)
                return 0;
        else
        return 1;
}


void showgolf(const golf & g)
{
        cout << "\nFull name: " << g.fullname << "\n";
        cout << "Handicap: " << g.handicap << "\n";
}

Frozen grid in CView of SDI splitter

$
0
0
I have been working with both Chris Mander's MFC grid and the Ultimate Grid.

See for details:
The Ultimate Grid Beginner's Guide By The Ultimate Toolbox, 25 Aug 2007
http://www.codeproject.com/Articles/...rid_in_a_CView

MFC Grid control 2.27 By Chris Maunder, 6 May 2010
http://www.codeproject.com/Articles/...d-control-2-27

Both of these grid controls work nicely in a SDI CView windows. But when I create a split window using CSplitterWnd and the following code in an attempt to create a split window with a CListView and and a CView using this code:

Code:

// in CMainFrame.h

// Attributes
public:
        CSplitterWnd m_wndSplitter;

//..
// in CMainFrame.cpp
//..

BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
        CSize size(0, 0);

        // create a splitter with 2 columns
        if (!m_wndSplitter.CreateStatic(this, 1, 2))
        {
                TRACE0("Failed to CreateStaticSplitter\n");
                return FALSE;
        }

        // add the first splitter pane - the view in column 0 row 0
    if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CSelector), CSize(100, 100), pContext))
        {
                TRACE0("Failed to create CSelector pane\n");
                return FALSE;
        }

        // add the second splitter pane - the view in column 1 row 0
    if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CUltSplitView), size, pContext))
        {
                TRACE0("Failed to create CUltSplitView pane\n");
                return FALSE;
        }

          m_wndSplitter.SetActivePane(0, 0);
        m_wndSplitter.EnableWindow(FALSE);

    return TRUE;

}// OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)

the grid in the CView window appears but is frozen in both instances.

I suspect there is some notification necessary to for the grid to send and receive messages from the split CView window, but I cannot figure out how to implement this notification.

Unfortunately, even a demo application would be too large to append, but for anyone that is interested, the split method is encapsulated in the code I've presented here and the implementation of both grid controls is well explained in the links provided.

Any help or suggestions would be greatly appreciated.

help to write c prog

$
0
0
hey ppl, I'm totally new to programming plz help. I'm expected to write a c program for this question for homework.

Using these header files
#include <stdio.h>
#include <conio.h>

Ques
Write a program that will prompt the user to enter an integer value and a character code to indicate whether they want to do a Kilogram to Pounds conversion (A) or a Pounds to Kilogram (B) conversion. Note that 1 kg = 2.2 pounds. The program should then do the necessary conversion indicated by the code and display the newly converted value to the screen.

Using Rebar

$
0
0
The following code I used to create a toolbar in rebar.wndOwner is a dialog box.
The following is the status
1)Tool bar works in the dialog box, but withhout tool tips which I added in the resource editor for IDR_TOOLBAR1.
(as prompt = \nClose like that)
2) My code to add the toolbar to rebar band is failing. As indicated in the last line of the code.

Please note that I am using ATL & WTL classes.


void CreateRebarWithToolbar(CWindow& wndOwner,CReBarCtrlT<CWindow>& rbCtrl,CToolBarCtrlT<CWindow>& tbCtrl)
{
DWORD dwStyle = WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS| WS_CLIPCHILDREN|RBS_VARHEIGHT|CCS_NODIVIDER;
DWORD dwExStyle = WS_EX_TOOLWINDOW;

rbCtrl.Create(wndOwner,0,0,dwStyle,dwExStyle);
ATLASSERT(rbCtrl.IsWindow());

REBARINFO rbi;
rbi.cbSize = sizeof(REBARINFO);
rbi.fMask = 0;
rbi.himl = (HIMAGELIST)NULL;

ATLVERIFY(rbCtrl.SetBarInfo(&rbi));
//I tried this also
//rbCtrl = CFrameWindowImplBase<>::CreateSimpleReBarCtrl(wndOwner);
//ATLASSERT(rbCtrl.IsWindow()); works fine!

tbCtrl = CFrameWindowImplBase<>::CreateSimpleToolBarCtrl(wndOwner, IDR_TOOLBAR1, FALSE,ATL_SIMPLE_TOOLBAR_STYLE );
ATLASSERT(tbCtrl.IsWindow());
DWORD dwBtnSize = tbCtrl.GetButtonSize();

REBARBANDINFO rbBand;
::ZeroMemory(&rbBand,sizeof(REBARBANDINFO));
rbBand.cbSize = sizeof(REBARBANDINFO);
rbBand.lpText = _T("Tool Bar");
rbBand.hwndChild = tbCtrl.m_hWnd;
rbBand.cxMinChild = 0;
rbBand.cyMinChild = HIWORD(dwBtnSize);
rbBand.cx = 250;

ATLASSERT(::IsWindow(rbBand.hwndChild));

BOOL b = rbCtrl.AddBand(&rbBand);//b is FALSE


}

Access violation reading void* assigned dynamically allocated value inside function

$
0
0
Hi guys,

I'm hoping someone can explain the behavior of this code for me. I don't understand why the void pointer passed to testb doesn't continue pointing to the allocated integer after the function call returns.

Code:

#include <stdio.h>
#include <iostream>

void* testa()
{
        return new int(1);
}

void testb(void* test)
{
        test = (void*) new int(2);

        printf("Value of void* in testb: %u\n", *static_cast<unsigned int*>(test)); // okay
}

int _tmain(int argc, _TCHAR* argv[])
{
        void* testaptr = testa();
        printf("Value of void*: %u\n", *static_cast<unsigned int*>(testaptr)); // okay

        void* testbptr = nullptr;
        testb(testbptr);
        printf("Value of void*: %u\n", *static_cast<unsigned int*>(testbptr)); // access violation reading testbptr

        getchar();

        return 0;
}

Thanks a lot.

Should precompiled header files also be included in source header files?

$
0
0
When including a header file in stdafx.h, should that file still be included in the source file where it is actually used?

I've done lots of searching but I can't convince myself either way...

If it is included in both places, is the one in the source file ignored?

Cheers,
AnotherMuggle.

Creating DLL with Web Browser Embedded

$
0
0
Hello all,

I want to develop a DLL that has a web browser embedded in it. In the past i have created MFC dialog app using CDHtmlDialog. With that experience what i want to achieve is create a DLL that has browser embedded in it, and then load this DLL into a web browser like IE, Chrome or Firefox.

I want all the GUI elements to be developed in HTML with some JavaScript(JS) added. Now i want to trigger the controls in the HTML/JS using the C++ code that runs the DLL. And also i should be able to launch this DLL on another web browser and display the HTML/JS controls.

Is this possible to do?

The reason why i want it this way is because the C++ code in the DLL will talk with another C++ DLL and take instructions on how and when to show the HTML/JS controls.

As i said earlier, i have worked with CDHtmlDialog in MFC Dialog app. But in this case i don't need any MFC controls. All i need is a Web Browser capability like the one CDHtmlDialog provided. And also this should be launchable from with in another web browser like IE or Chrome or Firefox.

Please let me know of any examples that does similar things.

Thanks in advance.

Exported DLL symbol validity

$
0
0
I'm building a cross-platform library which links to some other 3rd party libraries at run time (i.e. on Windows, the other libs will be available as DLLs whereas on Linux / OS-X etc they'd be shared objects, which are similar). For the sake of argument, one of those libraries is called "jack".

Obviously, our app can't guarantee which version of the other libs will be on the user's system (or even that they'll be installed at all). So our code is littered with statements like this:-

Code:

        if (!jack_port_type_get_buffer_size) {
                warning << _("This version of JACK is old - you should upgrade to a newer version") << endmsg;
        } else {
                some_var = jack_port_type_get_buffer_size();
        }

We link to the latest version of jack, where that symbol is declared like so:-

Code:

        size_t jack_port_type_get_buffer_size();
One problem is that it doesn't even seem to be an exported symbol (although that wouldn't affect the other platform builds). But apart from that, our customer might have an old copy of jack installed or even no copy! We seem to be making the assumption that if our customer has an up-to-date version, jack_port_type_get_buffer_size will be set to a valid address - but in all other case it'll be magically set to zero (there's nothing in our code that sets it to zero).

This whole strategy seems rather flaky to me. Am I worrying unnecessarily?

Please, need help with C++ codes..!

$
0
0
Write a C++ program that takes as inputs: an employee name, the hourly rate, and the number of
hours s/he worked in the last week. The program then outputs all entered information in addition
to the salary of the employee for the last week. The steps are as follows:

(1) Write C++ statements that include the header files iostream and string.

(2) Write C++ statements that declare the following variables: name of type string,
hourlyRate of type double, hoursWorked of type int, and salary of type double.
Write a C++ statement that computes the salary of the employee and stores the result in
the variable salary.

(3) Write a C++ statement(s) that output(s) the value of name, hourlyRate, hoursWorked,
and salary with the appropriate text. For example, if the values of name, hourlyRate,
hoursWorked are “Nancy”, 10.5 and 20, respectively, the outputs should be similar to
below:
Hello, Nancy! The last week you worked for 20 hours. Knowing that your hourly rate is
10.5 dollars, your salary for the last week is 210 dollars.

length of a string

$
0
0
Does anyone know a way to get the length of a string? I have tried:

str.length
str.size
strlen()

Bob

Code:


// Exercise in string manipulation

#include <iostream>
#include <string>

void prtname(std::string str);

using namespace std;

int main()
{
        string input;

        cout << "Please enter the name of a bird with long legs: ";

        cin >> input;

        prtname(input);

        return 0;
}

void prtname(std::string str)
{
        cout << "The birds name is: " << str;
        cout << "The lenght of the name is: " << str.length;
}

Best complete C++ tutorial series on YouTube?

$
0
0
I'm looking into writing games, and I thought I'd start learning C++, now don't assume I'm wanting to write games next week as you'd be wrong, I talking in one, two or three years when I'm fluent in C++ or at least I feel confident enough to attempt at writing games or learning OpenGL and such.

Before all of that I'm going to need some tutorials, I've come across the very good set of tutorials on the website http://www.learncpp.com/ in which I've read though the first section, however I'm more interested in video tutorials and I came across a series by "CodingMadeEasy", the series as a whole is nine hours which I feel is a little short so I skipped to the "last" video to read a comment which was posted eleven months ago asking when will the next video be released, with the reply "next week" which presumably didn't happen.

I'd really appreciate it if somebody could link me to a complete YouTube series which will hopefully get me enough knowledge to maybe start on OpenGL or go on to C++11.

How to use BTNS_AUTOSIZE

$
0
0
I want to control my toolbar dynamically.

First I added tool bar with style including TBSTYLE_EX_MIXEDBUTTONS | TBSTYLE_LIST.
Then added the tool bar to a rebar. I added tool tips by handling TTN_GETDISPINFO.

Everything works fine. But when I try to add text to right of the button, the text
gets added but button size is not automatically changing.

The following code is not working .

void SetToolbarText(HWND& hwndToolbar,LPTSTR szText)
{
ATLASSERT(::IsWindow(hwndToolbar));
TBBUTTONINFO tbbi = { 0 };
tbbi.cbSize = sizeof(TBBUTTONINFO);
tbbi.dwMask = TBIF_TEXT;// | TBIF_SIZE;//if I add TBIF_SIZE code will work!
tbbi.cchText = 0;
tbbi.cx = 200;
tbbi.fsState = 0;
tbbi.fsStyle = tbbi.fsStyle | BTNS_SHOWTEXT | BTNS_AUTOSIZE ;//TBSTYLE_AUTOSIZE
//tbbi.fsStyle = tbbi.fsStyle | BTNS_SHOWTEXT | TBSTYLE_AUTOSIZE ;//TBSTYLE_AUTOSIZE
tbbi.idCommand = 0;
tbbi.iImage = 0;
tbbi.lParam = 0;
tbbi.pszText = szText;//szText is _T("ABC")
BOOL b = (BOOL)::SendMessage(hwndToolbar, TB_SETBUTTONINFO, ID_BUTTON3, (LPARAM)&tbbi);
return;
}

Can anybody please help me?

_access function error

$
0
0
Just wonder is it possible that if the file exist, this function below will fail by returning non-zero value?
_access( INIFilename, 00 )

00 - check for Existence only

I noticed that sometimes if even the file exist, the function will fail or return non-zero value.
So trying to find out and duplicate this error. It tends to happen intermittently.
Any idea how can I find out what causing this error?

Code:

char INIFilename[256]="C:\temp\test.ini";
unsigned long Error = 0;
if( _access( INIFilename, 00 ) != 0 )
{
  Error= GetLastError(); 
  printf ("Failed to access INI file %s (%ul)", INIFilename, Error);
}

parsing a line for words...

$
0
0
Hi,
I'm getting this when I compile my program. Then, when the program runs I get an error. I assume it is because I have the warning for this problem. How can get around this error.

warning C4172: returning address of local variable or temporary

Code:


#include <iostream>
#include <cstring>

using namespace std;


char* parse_words(char* pstr, int strp);


int main()
{
        char* strin("This is the string to be parsed");
        cout << " String is: " << strin << " Length is: " << strlen(strin) << "\n\nParsing...\n";

        /* cout << "Please enter a string to parse word-by-word: \n";
        cin >> strin;
        cout << "This is the string entered: " << strin << " \n.";
        */
        //char * p(nullptr);
        char* p = parse_words(strin, strlen(strin));
        //char* p = parse(s1);
        while (p)
        {
                std::cout << p << "\n.";
                delete [] p;
                p = parse_words(nullptr, strlen(strin));
        }
        return 0;

}
char* parse_words(char* pstr, int strp)
{
        static int start(0);
        static int len(strp);
        cout << "Value of len: " << len << '\n';
        int lenpm(len);
        int pos(0);
        int x;
        char* pReturn(nullptr);
        int holdlen(20);
        char holdarea[20];

        cout << "Start start loop\n";
        for (start; start <= len; start++)
        {
                cout << "Start loop: \n";
                for (x = 0; x <= holdlen; x++)
                {
                        holdarea[x] = ' ';
                }
                if (*pstr != ' ')
                        while (*pstr != ' ')
                        {
                                holdarea[x] = *pstr;
                                x++;
                                *pstr++;
                                start++;
                        }
                return holdarea;
        }

        return pReturn;

}

Viewing all 3029 articles
Browse latest View live


Latest Images