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

Converting C To C++ - It Worked In Original C But Not In Converted C++?


MFC and STD::STRING not compatable ???

$
0
0
Im maintaining a legacy app in VC6 aka VS6 (release date 1998, wikipedia), don't have time to upgrade it now. I have found a previous bug in this version I think I found another.


I'm trying to write objects to disk and read them back. This code works in a counsel app WITHOUT MFC. I can't get it to work in an MFC SDI FORVIEW app.

I created an SDI FORMVIEW APP and place a Listbox and Button on the screen. I placed the following code in the button message handler. This is just a test App to test the code.


Note the list function takes a pointer to the listbox so as you all know you have to create a control variable in classwizard to the listbox

In a counsel app I can add and read objects fine, but in the MFC version all I get is junk in the list box and message box.

Can you guys try it in a newer Visual Studio? Or am I overlooking something? I don't use std::string much as I'm more of a CString guy, but I'm very interested in writing/reading std::cstring obects to file since I haven't found a way to write CString objects to file and accesses the files in random access mode.


Thanks in advance.

I have version 2003 profesional but haven't installed it. If some one has it please try it on that verision. It's a big project and porting it might cause issues.


Code:

//top of file
#include "stdafx.h"

//......


#include <string>
#include <iostream>
#include <fstream>

using namespace std;

void MYFORMVIEW::OnButtonDbCpp()
{





        class Person{

                public:
       
                std::string m_Name;
                int m_Age;
                int m_Ratings;


                void InitPerson( std::string Name, int Age, int Ratings){
                                m_Name = Name;
                                m_Age  = Age;
                                m_Ratings = Ratings;
                };
        };
        class Person_IO{

        public:

                void WritePerson( Person P, std::string Name, int Age, int Ratings){
                                P.m_Name = Name;
                                P.m_Age  = Age;
                                P.m_Ratings = Ratings;

                                ofstream outfile;

                                outfile.open("persfile.dat", ios::app | ios::binary);

                               
                                //file.read((char*)&obj, sizeof(obj)); //doesn't work either       
                                outfile.write(reinterpret_cast<char*>(&P),sizeof(P));

                                outfile.flush();

                                outfile.close();
                }

                void ReadAllPersons( Person P, CListBox* pList){
                                //P.m_Name = Name;
                                //P.m_Age  = Age;
                                //P.m_Ratings = Ratings;

                                ifstream infile;

                                infile.open("persfile.dat",  ios::binary);

                               
                                while(1){
                                       
                                        //file.read((char*)&obj, sizeof(obj)); //doesn't work either       
                                        infile.read(reinterpret_cast<char*>(&P),sizeof(P));
                                        if(infile.eof()) break;
                                        pList->AddString(P.m_Name.c_str());

                                        ::AfxMessageBox(P.m_Name.c_str());
                                };

                                infile.close();

                               
                }




        };

        Person  Per;
        Person_IO P_IO;

        P_IO.WritePerson( Per, "Joe Baker",42, 125);
        P_IO.WritePerson( Per, "Sam Valet",52, 12);
        P_IO.WritePerson( Per, "Don Tracy",55, 912);


        P_IO.ReadAllPersons( Per, &m_CList1);


       
               
}

Changing background Color of CToolbar in MFC

$
0
0
Can anyone provide working code for changing background color of CToolBar? I drill down many links but nothing effective

enum or static const

$
0
0
I have some legacy code, where they use the magic numbers to index arrays.

Snippet is :

Code:

if(pLossMultiRaster || pSBATrafficLossMultiRaster)
{
    //        NOTE - SPECIFIC ORDER IS IMPORTANT!
    INT_PTR *SBAarray[12];

    SBAarray[0] = reinterpret_cast<INT_PTR*>(pSBAControlLossMultiRaster);
    SBAarray[1] = reinterpret_cast<INT_PTR*>(pSBABestControlBeamIndexMultiRaster);

Im thinking to replace it with enum, Or static const int .. Any comments on Which one is better to use the enum or static const ?

Thanks
pdk

Make a good like button.

$
0
0
How to make a like button, that show who has like my post, on a social media website.

Can we use OnDrawItem for dynamically created CStatic objects ?

$
0
0
The main problem is a CStatic Object is created dynamically & when I'm changing the background of entire dialog to white, the background of dialog changes except the CStatic Object.

Also if CStatic Object background is white, then it is not visible on the screen.

How To: Prevent duplicate coding

$
0
0
I am rather new in programming and wonder how to compact the code I wrote for using a flexible number of CJMCU-8110 connected to my NodeMCU. In the attached test code below I have 2 connected, but in the near future I want to expand to 3 or 4 and would like to drive that by a variable (f.i. int SensorNumber = 2) instead of duplicating the code for each sensor like I did in the example.

Who can guide me to a solution?

Code:

#include <Arduino.h>
#include <Wire.h>    // I2C library
#include "ccs811.h"  // CCS811 library
#include "ClosedCube_HDC1080.h"

CCS811 ccs811_1;
CCS811 ccs811_2;

ClosedCube_HDC1080 HDC1080_1;
ClosedCube_HDC1080 HDC1080_2;

int SDApin;
int SCLpin = D1;

HDC1080_SerialNumber sernum;
char format[12];
bool vBootphase = true;
uint16_t eco2, etvoc, errstat, raw;

void setup() {Serial.begin(115200); while(!Serial){;}}

void loop()
{
  if (vBootphase == true)
  {
    // Channel 1: Setup
    SDApin = D2;
    Wire.begin(SDApin, SCLpin);
    delay(500);
    // ** CCS811 **
    Serial.println("");
    Serial.println("*** CCS1 ***");
    Serial.print("CCS :");
    ccs811_1.set_i2cdelay(50);
    ccs811_1.begin();
    delay(500);
    ccs811_1.start(CCS811_MODE_1SEC);
    delay(1000);
    Serial.print("setup: hardware    version: "); Serial.println(ccs811_1.hardware_version(),HEX);
    Serial.print("setup: bootloader  version: "); Serial.println(ccs811_1.bootloader_version(),HEX);
    Serial.print("setup: application version: "); Serial.println(ccs811_1.application_version(),HEX);
    // HDC1080
    HDC1080_1.begin(0x40);
    Serial.print("Manufacturer ID=0x");
    Serial.println(HDC1080_1.readManufacturerId(), HEX); // 0x5449 ID of Texas Instruments
    Serial.print("Device ID=0x");
    Serial.println(HDC1080_1.readDeviceId(), HEX); // 0x1050 ID of the device
    Serial.print("Device Serial Number=");
    sernum = HDC1080_1.readSerialNumber();
    sprintf(format, "%02X-%04X-%04X", sernum.serialFirst, sernum.serialMid, sernum.serialLast);
    Serial.println(format);

    // Channel 2: Setup
    SDApin = D6;
    Wire.begin(SDApin, SCLpin);
    delay(500);
    // ** CCS811 **
    Serial.println("*** CCS2 ***");
    // Print CCS811 versions
    Serial.print("CCS2 :");
    ccs811_2.set_i2cdelay(50);
    ccs811_2.begin();
    delay(500);
    ccs811_2.start(CCS811_MODE_1SEC);
    delay(1000);
    Serial.print("setup: hardware    version: "); Serial.println(ccs811_2.hardware_version(),HEX);
    Serial.print("setup: bootloader  version: "); Serial.println(ccs811_2.bootloader_version(),HEX);
    Serial.print("setup: application version: "); Serial.println(ccs811_2.application_version(),HEX);
    // HDC1080
    HDC1080_2.begin(0x40);
    Serial.print("Manufacturer ID=0x");
    Serial.println(HDC1080_2.readManufacturerId(), HEX); // 0x5449 ID of Texas Instruments
    Serial.print("Device ID=0x");
    Serial.println(HDC1080_2.readDeviceId(), HEX); // 0x1050 ID of the device
    Serial.print("Device Serial Number=");
    sernum = HDC1080_2.readSerialNumber();
    sprintf(format, "%02X-%04X-%04X", sernum.serialFirst, sernum.serialMid, sernum.serialLast);
    Serial.println(format);

    vBootphase = false;
  }
  else
  {
    // Channel 1
    SDApin = D2;
    Wire.begin(SDApin, SCLpin);
    delay(500);
    // ** CCS811 **
    Serial.print("\nSensor connected on: ");
    Serial.print("SDA - ");Serial.print(SDApin); Serial.print(" | SCL - ");Serial.print(SCLpin);
    Serial.print("\n");
    ccs811_1.read(&eco2,&etvoc,&errstat,&raw);
    delay(500);
    Serial.print("ErrStat: ");Serial.print(errstat);Serial.print(" | ");Serial.println(ccs811_1.errstat_str(errstat));
    if(!errstat==CCS811_ERRSTAT_OK)
    {
      Serial.print("CCS811-1: ");
      Serial.println("Failed to read from sensor");
      ccs811_1.begin();
      delay(500);
      ccs811_1.start(CCS811_MODE_1SEC);
    }
    else
    {
      Serial.print("CCS811-1: ");
      Serial.print("eco2=");    Serial.print(eco2);    Serial.print(" ppm | ");
      Serial.print("etvoc=");  Serial.print(etvoc);    Serial.print(" ppb");
      Serial.print("\n");
    }
    // ** HDC1080 **
    Serial.print("T="); Serial.print(HDC1080_1.readTemperature()); Serial.print("C");
    Serial.print(", RH="); Serial.print(HDC1080_1.readHumidity()); Serial.println("%");

    // Channel 2
    SDApin = D6;
    Wire.begin(SDApin, SCLpin);
    delay(500);
    // ** CCS811 **
    Serial.print("Sensor connected on: ");
    Serial.print("SDA - ");Serial.print(SDApin); Serial.print(" | SCL - ");Serial.print(SCLpin);
    Serial.print("\n");
    ccs811_2.read(&eco2,&etvoc,&errstat,&raw);
    delay(500);
    Serial.print("ErrStat: ");Serial.print(errstat);Serial.print(" | ");Serial.println(ccs811_2.errstat_str(errstat));
    if(errstat!=CCS811_ERRSTAT_OK)
    {
      Serial.print("CCS811-2: ");
      Serial.println("Failed to read from sensor");
      ccs811_1.begin();
      delay(500);
      ccs811_2.start(CCS811_MODE_1SEC);
    }
    else
    {
      Serial.print("CCS811-2: ");
      Serial.print("eco2=");    Serial.print(eco2);    Serial.print(" ppm | ");
      Serial.print("etvoc=");  Serial.print(etvoc);    Serial.print(" ppb");
      Serial.print("\n");
    }
    // ** HDC1080 **
    Serial.print("T="); Serial.print(HDC1080_1.readTemperature()); Serial.print("C");
    Serial.print(", RH="); Serial.print(HDC1080_1.readHumidity()); Serial.println("%");

    delay(10000);
  }
}

Trouble getting program to recieve simulated xinput

$
0
0
I have been writing a program which needs to simulate an input from a controller. I have been using SendInput() with a keyboard input and used VK_GAMEPAD_A as my test key.

Code:

void PressButton(WORD key, unsigned short time = 50)
{
    INPUT Input = { 0 };
    unsigned int size = sizeof(INPUT);
    WORD vKey = MapVirtualKey(key, 0);

    Input.type = INPUT_KEYBOARD;
    Input.ki.wScan = vKey;
    Input.ki.dwExtraInfo = GetMessageExtraInfo();
    Input.ki.dwFlags = KEYEVENTF_SCANCODE;
    SendInput(1, &Input, size);

    Sleep(100);
    ZeroMemory(&Input, size);
    Input.type = INPUT_KEYBOARD;
    Input.ki.wScan = vKey;
    Input.ki.dwExtraInfo = GetMessageExtraInfo();
    Input.ki.dwFlags = KEYEVENTF_SCANCODE;
    SendInput(1, &Input, size);
    Sleep(time);
}

When I run this code nothing happens. Is this a problem with my code or with the receiving program? Am I using the right keycode?

Also I will need to do joysticks and triggers. There will be a float or double as the input for those.

Caret not displayed in CEdit control with focus when dialog initially displayed

$
0
0
I have a CDialog derived dialog which has a CFormView derived member which has a number of CEdit derived controls placed on it.

Based on business rules at runtime one of the CEdit derived controls should receive the focus when the dialog is displayed. In the OnInitialUpdate override of the CFormView derived class (called from owning dialogs OnInitDialog method which returns FALSE to indicate that we have set the focus on a control) the specific control is determined and focus is set to that control with the following call:


PostMessage(WM_NEXTDLGCTL, (WPARAM)pFocusEdit->GetSafeHwnd(), TRUE);


When the dialog is displayed there is no caret displayed within the control. It is outlined in the blue colour showing that it has focus, if I start typing the text is displayed but still no caret. If I TAB to the next control the caret is displayed there and if I TAB back it is now displayed in the originally focused control.
Alternatively, after the dialog is initially displayed and the caret is not showing If I shift the active window to another app (e.g. visual studio) and then actiavte the app again then the caret does appear in the CEdit control.

Any suggestions as to how I can ensure that the desired CEdit control receives focus on display of the dialog and that the caret is displayed?

Thanks,

MSDN documentation unclear ?

$
0
0
I am trying to read directories from an EXFAT USB drive. And for this task, I have found here a good documentation: https://docs.microsoft.com/en-us/win...-specification

But seem that is unclear somehow, at least to me.

I have successfully read - Main and Backup Boot Sector Structure Table (https://docs.microsoft.com/en-us/win...ctor-structure), value by value.

And then, I have read - Cluster Heap Structure Table (https://docs.microsoft.com/en-us/win...heap-structure)


Code:

        const int nSize = dwSectorSize * 1 << nSectorsPerClusterShift;
        const int nCount = nClusterCount + 1;
        LONGLONG llPos = nClusterHeapOffset;
        LONGLONG nLimit = nClusterHeapOffset + ((nClusterCount - 1) * nSize);

        for (int i = 0; i < nCount; ++i)
        {
                file.Seek(llPos, CFile::begin);
                arrByte.RemoveAll();
                arrByte.SetSize(nSize);
                UINT nRet = file.Read(arrByte.GetData(), arrByte.GetSize());

                llPos += nSize;
                if (llPos > nLimit)
                        break;
        }

and for every cluster from cluster heap, I retrieved a CByteArray of 32768 bytes. Fine by now. Now, there is another part: Directory Structure Table (https://docs.microsoft.com/en-us/win...tory-structure)

Here I am stuck. I guess I can read the directory (or files) from this cluster, one by one. Theoretically, I should read every cluster from 32 to 32 bytes, according Directory Structure Table, which gave me 1024 (32768 / 32). But in this cluster, I don't know how to consider those bytes in order to have a directory (or file). More over, I don't know how to compute N (for DirectoryEntry[N–1]).

The documentation says: N, the number of DirectoryEntry fields, is the size, in bytes, of the cluster chain which contains the given directory, divided by the size of a DirectoryEntry field, 32 bytes.

From documentation: A cluster chain is a series of clusters which provides space for recording the contents of files, directories, and other file system structures.

Now, how is: "cluster chain which contains the given directory" ? Can you help me a little bit ? I am stuck here for a while, and I don't know how to move on ...

How to do flat style of CEdit (EDITTEXT) and CComboBox in CDialog

$
0
0
Can any one tell/provide code snippet for making the CEdit(EDITTEXT box) and CComboBox of
flat style?

Coloring Rect of Create(lpszText,dwstyle,&rect,parentwnd,nID) white

$
0
0
I have below code

Code:

CStatic *text = new CStaic ;
CRect textrect(10,20,70,50);
MapDialogRect(&tectrect);

text -> Create(name.data(),WS_CHILD | WS_VISIBLE | SS_RIGHT,textrect,this);

The problem is text is displayed on rectangle with gray color. How can i paint that rectangle color to white?

[RESOLVED] How to do flat style of CEdit (EDITTEXT) and CComboBox in CDialog

$
0
0
Can any one tell/provide code snippet for making the CEdit(EDITTEXT box) and CComboBox of
flat style?

visual studio, resource file error : opened in another editor

$
0
0
Hello,

I have a resource file, and when i try to open, i get error saying, opened in another editor. (eventhough it is not opened anywhere else) !

thanks
pdk

DLL C++ and C#

$
0
0
Hi,

I'm writing a dll in C++ to get the serial hd, this is the code of the function:
Code:

__declspec(dllexport) char* __stdcall char* GetSerialHD()
{
    WmiQueryResult res = getWmiQueryResult(L"SELECT SerialNumber FROM Win32_PhysicalMedia", L"SerialNumber");
    char* ret = NULL;
    std::string strValue;
    char* strReturn = NULL;
    for (const auto& item : res.ResultList) {
          strValue.assign(item.begin(), item.end());
          ULONG ulSize = strlen(MyString) + sizeof(char);
          strReturn = (char*)::CoTaskMemAlloc(ulSize);
          strcpy(strReturn, strValue.c_str());
          break;
    }
    return strReturn;
}

The dll function calls it from an application written in C#:

Code:

[DllImport("mydll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string GetSerialHD();

...
string GetHD = GetSerialHD();

function GetSerialHD() always returns null, but the same code in a console application C++ for testing works well.

thanks

Erase an stl element within the or loop

$
0
0
Hello

I have the ollowing for loops, inside the second for loop, i want to erase the second element based on some condition.
I know erasure invalidates the iterator. What is the nice way to do this ?

Code:

        for (auto& sulCell : nCellList.sulCellList)
        {
                        bool bFirstMatch = false;

                        for (auto& tddCell : nCellList.tddCellList)
                        {
                              if(condition)
                              erase(tddCell);
                          }
      }

FLAT CEdit(EditBox)

$
0
0
Just a quick question. I am able to achieve flat editbox through CreateEx already discussed in previous thread.But question here again is why i am not able to achieve it resource editor although when i see editbox in resource edit it appears perfectly flat but after compiling code ,box shown on screen has sunken edge , not able to understand why. Since in my application i have to do around 200 editboxes flat thats why i dont want to use CreareEx . I am using Visual studio 2015. In project settings Target platform version is 8.1 and Target Platform is Windows..I have windows 10 installed on my machine.

[RESOLVED] FLAT CEdit(EditBox)

$
0
0
Just a quick question. I am able to achieve flat editbox through CreateEx already discussed in previous thread.But question here again is why i am not able to achieve it resource editor although when i see editbox in resource edit it appears perfectly flat but after compiling code ,box shown on screen has sunken edge , not able to understand why. Since in my application i have to do around 200 editboxes flat thats why i dont want to use CreareEx . I am using Visual studio 2015. In project settings Target platform version is 8.1 and Target Platform is Windows..I have windows 10 installed on my machine.

Changing background Color of CBS_DROPDOWN CCombobox

$
0
0
Any idea how to quickly change background color of CBS_DROPDOWNLIST CComboBox to white. since CBS_DROPDOWN has white background, i also want CBS_DROPDOWNLIST to have white background.

Changing textColor of CMFCBUTTON in disabled state

$
0
0
I have the following code:
Code:

bool var;
m_button.EnableWindow(var);
If(var)
{
m_button.SetFaceColor((RGB(0,255,0),true);
m_button.SetTextColor((RGB(255,255,255)));
}
else
{
m_button.SetFaceColor((RGB(0,0,255),true));
m_button.SetTextColor((RGB(255,0,0)));
}

Issue is button face color changes correctly in both enabled and disabled state but text color does not change in disabled state.
Viewing all 3021 articles
Browse latest View live