Showing posts with label Cplus. Show all posts
Showing posts with label Cplus. Show all posts

Wednesday, May 29, 2013

SendMessage from modaless dialog to the view in SDI without document/view structure support--another method

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to send the "view" a message

you can realize it like this:

1. in ChildView.cpp
#include "ModalLessDlg.h"

void CChildView::OnModalLess() // show the modalless dialog
{

    CModalLessDlg* instance = new CModalLessDlg(this);
    instance->Create(CModalLessDlg::IDD,this);
    instance->PARENT = this;  
    instance->ShowWindow(1);

}


2. in ModalLessDlg.h

#include "ChildView.h"



public:

CChildView *PARENT;



3. in ChildView.h

public:

void     setDisplayText(CString src);

private:

CString   displayText;


4. in ChildView.cpp

CChildView::CChildView(): displayText(_T("zhiguang"))
{
}



void CChildView::setDisplayText(CString src)
{
    displayText=src;
    Invalidate(TRUE);
}



void CChildView::OnPaint() // show different results of image 
{


  CPaintDC dc(this); // device context for painting   
  CRect rect;
  GetClientRect (&rect);
  dc.DrawText (displayText, -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER);

}



5. in ModalLessDlg.cpp

void CModalLessDlg::OnBegin() // 
{

  CString str_sent="OnBegin is running!";
  PARENT->setDisplayText(str_sent);
}




that is all.

it is using ChildView as one parameter to construct the modaless dialog, then you can easily use the ChildView and its members to change the client area.



Tuesday, May 28, 2013

SendMessage from modaless dialog to the view in SDI without document/view structure support

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to send a text to the "view"

you can realize it like this:

1. in MainFrm.h, there is one protected variable:

protected: CChildView   m_wndView;


change it as public variable:

public: CChildView   m_wndView;


2. in ModalLessDlg.cpp:

#define WM_MY_DOSOME (WM_USER+1)


3. in ModalLessDlg.cpp:

void CModalLessDlg::OnBegin() // 
{
 // TODO: start
    
  CMainFrame   *pFrame=(CMainFrame*)(AfxGetApp()->m_pMainWnd); 
  char buf[]="I LOVE YOU";
 (pFrame->m_wndView).SendMessage(WM_MY_DOSOME,(WPARAM)buf,0);

}


4. In ChildView.h, add the following:

afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);//before DECLARE_MESSAGE_MAP()


5. in ChildView.cpp, add the following:

BEGIN_MESSAGE_MAP(CChildView, CWnd)
 // ...
    ON_MESSAGE(WM_MY_DOSOME,OnMyMessage)  //only need to add this line

 //...
END_MESSAGE_MAP()



//then realize the response function:

LRESULT CChildView::OnMyMessage(WPARAM iParam1,LPARAM iParam2)
{
   
 char *buf=(char *)iParam1; 
 CString str;
 str.Format("%s",buf);
 MessageBox(str);
 return 0L;

}


the function is only a test to see whether you can receive the text or not, you can also show it in the client area of the view through Invalidate() again in this OnMyMessage function.



modaless dialog refresh the view in SDI without document/view structure support

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to refresh the "view"

you can realize this like this:

1. in MainFrm.h, there is one protected variable:

protected: CChildView   m_wndView;

change it as public variable:

public: CChildView   m_wndView;

2. add one public variable for the ChildView.h:

public: int dlg_fresh;

initialize it in ChildView.cpp:

CChildView::CChildView()
{
 dlg_fresh=0;
}

3. in the response function of modalless dialog button, write like this:

//ModalLessDlg.cpp 

void CModalLessDlg::OnBegin() // stard the thread
{
 CMainFrame   *pFrame=(CMainFrame*)(AfxGetApp()->m_pMainWnd); // get the mainframe
 (pFrame->m_wndView).dlg_fresh=1; //set the flag
 (pFrame->m_wndView).Invalidate(); // refresh the view in the ChildView

}

4. in the ChildView.cpp, implement the OnPaint() like this:

//ChildView.cpp

void CChildView::OnPaint()
{
 CPaintDC dc(this); // device context for painting
 CRect rect;
 GetClientRect (&rect);
 if(dlg_fresh==0)
 {
  dc.DrawText (_T ("it is not the modaless dlg refreshing!"), -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER); 
 }
 else
 {
    dc.DrawText (_T ("it is the modaless dlg refreshing!"), -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER); 
       dlg_fresh=0;
 }
}


Monday, May 27, 2013

kernel event object and thread in MFC

one button to create the kernel event object and worker thread, and the other button to signal the event and terminate the thread.



UINT __cdecl MyThreadProc(LPVOID lpParameter) // thread generation function
{
   CEvent* pEvent = (CEvent*)(lpParameter);
   VERIFY(pEvent != NULL);
   // Wait for the event to be signaled
   ::WaitForSingleObject(pEvent->m_hObject, INFINITE);
   // Terminate the thread
   ::AfxEndThread(0, FALSE);
   return 0L;
}


void CModalLessDlg::OnBnClickedButton1() // start the thread
{
 // TODO: start
   pEvent = new CEvent(FALSE, FALSE);
   // Create a thread that will wait on the event
   //CWinThread* pThread;
   pThread = ::AfxBeginThread(&MyThreadProc, pEvent, 0, 0, CREATE_SUSPENDED, NULL);
   pThread->m_bAutoDelete = FALSE;
   pThread->ResumeThread();
  
   // show the status of thread
   CString st1="Thread started";
   SetDlgItemText(IDC_EDIT1, st1);
}


void CModalLessDlg::OnBnClickedButton2() // setevent and terminate the thread
{

    pEvent->SetEvent();
   // Wait for the thread to consume the event and return
    ::WaitForSingleObject(pThread->m_hThread, INFINITE);
    delete pThread;
    delete pEvent;
 // show the status of thread
    CString st2="Thread Terminated!";
    SetDlgItemText(IDC_EDIT1, st2);
}

edge detection based on sobel operator in MFC

void CChildView::OnEdge() // edge detection based on Sobel operators
{

 {
 int operx[3][3]={-1,0,1,-2,0,2,-1,0,1};//Sobel operators
 int opery[3][3]={1,2,1,0,0,0,-1,-2,-1};//Sobel operators
 int i,j;
 int p=0;
 int smx=0,smy=0;
 //CImage img_tem;
 //img_tem.Create(img_width,img_hight,24,0);
 for(i=0;i<img_hight;i++)
 {
  for(j=0;j<img_width;j++)
  {
   COLORREF cf = MyRGB(0,0,0);
   img_final.SetPixel(j,i,cf); //img_final is a member of this class, this is to reset it to zeros
         
  }
 }

 for(i=0;i<img_hight-2;i++)
 {
  for(j=0;j<img_width-2;j++)
  {
            smx=0;
   smy=0;
   for (int m=0; m<3; m++)
   {
      for (int n=0; n<3; n++)
      {  
      COLORREF rgb=img_new.GetPixel(j+n,i+m);
         int p=MyGetRValue(rgb);
                  smx=smx+p*operx[m][n];
                  smy=smy+p*opery[m][n];
      }
   }
   float G=smx*smx+smy*smy;
   int GD=(int)sqrt(G);
           
   if(GD>100) // threshold to determine whether it is an edge
   {
         COLORREF cf = MyRGB(255,255,255);
         img_final.SetPixel(j+1,i+1,cf);
 
   }
  }
 }
  
   Invalidate(); //call the OnPaint to show the result

}


basic image processing in MFC

Everybody knows that MFC+OpenCV is very convenient for image processing. But how about only using MFC? Most of the operation for image processing is based on bitmap in previous MFC version, say VC++6.0.

In VS2008, there is already CImage class, which could greatly facilitate the image processing.
 (1) get basic info of one image
  #include <atlimage.h>
  ...
  CImage img; //image object
  img.Load(FilePathName); // load a local image
  img_hight=img.GetHeight();//get hight
  img_width=img.GetWidth();//get width
  img_bits=img.GetBPP();//get bit counts for each pixel, say 8,24,32...
  COLORREF rgb=img.GetPixel(10,10);// get the pixel color
 

  CImage img_new; //another image object
  img_new.Create(img_width, img_hight, 24, 0);//create a image with the same size
  img.SetPixel(10,10,rgb);// set the pixel color

(2) get the r,g,b value from the COLORREF value:

#define MyGetRValue(rgb) ((BYTE)(rgb))
#define MyGetGValue(rgb) ((BYTE)(((WORD)(rgb)) >> 8))
#define MyGetBValue(rgb) ((BYTE)((rgb)>>16))

 COLORREF rgb=img.GetPixel(j,i);
 int r = MyGetRValue(rgb);
 int g=MyGetGValue(rgb);
 int b=MyGetBValue(rgb);

(3) convert the 24bit color image into gray image:

 #define MyRGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)))

 BYTE cl = (BYTE)(0.299 * r + 0.587 * g + 0.114 * b);
 int clr=(int)cl;
 COLORREF cf = MyRGB(clr,clr,clr);
  img_gray.SetPixel(j,i,cf);


 
 

Sunday, May 26, 2013

read and write .ini file in MFC

Sometimes we need to configure the controls on the dialog based on the .ini and we may also need to save the final control values on the dialog to the same file in MFC, we can do that like this:

user.ini
[initialize]                   ;section name
m_listbox=0               ;key and int value       
name=zhiguang          ;key and string value


(1) example to initialize the controls on the dialog

BOOL CModalDlg::OnInitDialog() // read values from the .ini file
{
 
  CDialog::OnInitDialog();
  CString  iniFilePath;
  iniFilePath=".//ini//user.ini";
  // read ini for listbox
  int  list_pos; 
  list_pos=GetPrivateProfileInt("initialize","m_listbox",0,iniFilePath);
  m_listbox.AddString(_T("MIT"));
  m_listbox.AddString(_T("I.PAC"));
  m_listbox.AddString(_T("CASEM"));
  m_listbox.AddString(_T("Genric Power"));
  m_listbox.SetCurSel(list_pos);
 
  // read ini for edit
  CString  str_edit; 
  GetPrivateProfileString("initialize","IDC_EDIT1","",str_edit.GetBuffer(MAX_PATH),MAX_PATH,iniFilePath);
  SetDlgItemText(IDC_EDIT1, str_edit);

  // read ini for checkbox
  int  check_val; 
  check_val=GetPrivateProfileInt("initialize","m_check",0,iniFilePath);
  m_check.SetCheck(check_val);
 
  // read ini for radio
  int  radio_val; 
  radio_val=GetPrivateProfileInt("initialize","IDC_RADIO1",0,iniFilePath);
  if(radio_val==1)
  ((CButton *)GetDlgItem(IDC_RADIO1))->SetCheck(TRUE);
  else
  ((CButton *)GetDlgItem(IDC_RADIO2))->SetCheck(TRUE);

  return TRUE;
}


(2) example to update the control values on the dialog back to the same .ini file.

void CModalDlg::OnBnClickedOk() //save the values to the .ini file
{
 CString  iniFilePath;
    iniFilePath=".//ini//user.ini";
 //write ini for listbox
 int list_pos=m_listbox.GetCurSel();
 CString str_pos;
 str_pos.Format("%d",list_pos);
 WritePrivateProfileString("initialize","m_listbox",str_pos,iniFilePath);
 //write ini for editbox
 CString str_edit;
 GetDlgItemText(IDC_EDIT1, str_edit);
 WritePrivateProfileString("initialize","IDC_EDIT1",str_edit,iniFilePath);
   // read ini for checkbox
    int  check_val; 
    check_val=m_check.GetCheck();
 CString str_check;
 str_check.Format("%d",check_val);
 WritePrivateProfileString("initialize","m_check",str_check,iniFilePath);
   // read ini for radio button
    int  radio_val; 
    radio_val=((CButton *)GetDlgItem(IDC_RADIO1))->GetCheck();
 CString str_radio;
 str_radio.Format("%d",radio_val);
 WritePrivateProfileString("initialize","IDC_RADIO1",str_radio,iniFilePath);

 OnOK();
}


To read the file, we have  GetPrivateProfileString and GetPrivateProfileInt for String and Int values, to write the file , we only have WritePrivateProfileString, so we should convert the format of the value into CString first before writing

modal and modalless dialog in MFC

For both cases, you should create one dialog template, which could be done in the resource explorer

Modal Dialog
1. then create one class ModalDlg for modal dialog using this dialog template, and the CModalDlg.cpp and CModalDlg.h would be generated.

2. in the file where you want to show the modal dialog, first include the "ModalDlg.h", then in this file, you could use the following code :

void CChildView::OnModal() // show the modal dialog
{
 CModalDlg dlg;
 dlg.DoModal();
}


ModalLess Dialog

1. then create one class ModalLessDlg for modalless dialog using this dialog template, and the CModalLessDlg.cpp and CModalLessDlg.h would be generated.

2. in the file where you want to show the modalless dialog, first include the "ModalLessDlg.h", then in this file, you could use the following code :

void CChildView::OnModalLess() // show the modalless dialog
{
 CModalLessDlg *lsdlg=new CModalLessDlg;
 lsdlg->Create(IDD_DIALOG2,NULL);//IDD_DIALOG2 is the ID of dialog template you created
 lsdlg->ShowWindow(SW_SHOW);

 }


For both dialogs, if you want to initialize some parameters for all the controls on them, you can do that by overriding the  BOOL CModalDlg::OnInitDialog(){}  or  BOOL CModalLessDlg::OnInitDialog() {}





Thursday, April 4, 2013

tranverse files under one directory using C++ on ubuntu

#include <string>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include </usr/include/i386-linux-gnu/sys/types.h>
#include </usr/include/i386-linux-gnu/sys/stat.h>
#include <dirent.h>
#include <errno.h>
using namespace std;
int main(void)
{
   DIR *dp;
   int n=0;
   int len=0;
   struct dirent *dirp;
   string str0;
   dp=opendir("/home/HSS/topic_modeling/topic_1/");

   while((dirp=readdir(dp))!=NULL)
   {  
      str0=string(dirp->d_name);
      len=str0.size();
      if( len>4)
// for txt files and this will filter out the '.' and '..' file
      {
            // do what you want to do !
      }
   }
return 0;
}

Tuesday, April 2, 2013

Standard C++

1. <string> is the C++ version for string type, <cstring> is the C++ version for string in C, <string.h>is the C version;

2.
 
   // In C, it is correct: 
         int *pr=NULL;
   // in C++, it is correct:
         int *pr=0;
   // if you want keep
          int *pr=NULL;
   //in C++ code, you should  #include<cstdlib>
3.  // 1)
 
            int a=10;
            int b=20;
            int const  *pt=&a; // same as: const int  *pt=&a ;
            *pt=11;  //error
             pt=&b;  // correct
      //2) 
 
            int a=10;
            int b=20;
            int *const  pt=&a;
            *pt=11;  //correct
             pt=&b;  // error
4. conversion between string and char
 
      //1)
          char * ch="caozhiguang";
          string str(ch); // from char to string;
           string str=ch; // same with above
      //2)
           string str("caozhiguang");
           char *ch;
           ch=str.c_str(); // from string to char;
5. avoid repeating include, also a  better file framework(at least for me)
 
    //Zhiguang.h
    #include <string>
    using namespace std;
    #ifndef  ZHIGUANG_H
    #define ZHIGUANG_H
       Class Zhiguang
       {
             public:
                     Zhiguang();
                     Zhiguang(string the_name, string the_addr);
                     string getinfo();
             private:
                     string name;
                     string address;
                     static double salary;
        }
    #endif

  //Zhiguang.cpp
  //you'd better initialize the static var in this file
  #include  "Zhiguang.h"
  salary=3500; //initialize the static var;
  Zhiguang::Zhiguang() { }
  Zhiguang::Zhiguang(string the_name, string the_addr)  { }
  string Zhiguang::getinfo(){    }

  //main.cpp
  #include "Zhiguang.h" // no need to include the cpp file
  using namespace std;
  int main()
  {
     Zhiguang zg;
    // do whatever you want
   }

6.  create one object for the class

 
   //1)  
         Zhiguang zg;
         zg.name;
         zg.address;
         zg.getinfo();
   //2) 
         Zhiguang zg=Zhiguang();
         zg.name;
         zg.address;
         zg.getinfo();

   //3)
         Zhiguang *zg=new Zhiguang();
         zg->name;
         zg->address;
         zg->getinfo();

7. default constructor needed to initialize members of built-in type

 
    Zhiguang() : name("zhiguang"), address("Singapore"){  }

   Note: for the real initialize order, it would be based on the declaration order in the class declaration.
   e.g:  
 
                private:
                     string address;
                     string name;
            in this case, the default constructor would initialize the address first even it is listed in the second  place in the constructor.

8.  1) if the member method is const, it means it can not change the object's member variable;
     2) for const member, there should be keyword const both in declaration and definition;
     3) the const object can only use its const member, while non-const object can access both const and non-const members;
     4) for non-const member method, this could not be changed while *this could;
          for const member method,  both this and *this could not be changed.




Thursday, February 28, 2013

Traverse all the files under one folders using matlab and C++ on windows

I usually need to process batches of files in my work. sometimes use matlab, some times use C++:

1. For MATLAB, it is very easy:

clear;
clc;
close all;
MyDir='D:\Matlab_Code\RA_6\recent-valid\'; 
% the folder where the targeted files are stored, do not forget the '\' in the end;
AllFileName=dir([MyDir,'*.txt']);
% AllFileName it is a array whose each element is a structure with many attributes
% all the infomation about txt files would be included in AllFilename
% You can even get the numbers of files just by size the AllFileName without traversing all the files
for i=1:length(AllFileName)
     Fid=fopen([MyDir,AllFileName(i).name]); % there are many optional parameters  you can choose
     Content=fgetl(Fid);
     while ischar(Content)
          Str= Content;
          % add your code here
          Content=fgetl(Fid);% if you miss this, it could run into a dead loop
     end
     fclose(Fid);% never forget to close the file
 end



2. For C\C++ on windows, it is almost same:


#include 
#include 
#include 
using namespace std;
int main (void)
{

    _finddata_t fileDir; // it is included in io.h, much similar to the AllFileName in the matlab code

    char* dir="C:\\CZG\\Matlab_Code\\HSS\\*.m";

    // notice the end of the above line: 
    // if you write as  *.m, then only m file would be found
    // if you write as  *.m*, hen all the extention format start with m could be found, such as .mat, .m file could be found at the same time

     long lfDir;

    if((lfDir = _findfirst(dir,&fileDir))==-1l) // in case there is no m file found

       printf("No file is found\n"); 

    else{

           printf("file list:\n");

           do{

               printf("%s\n",fileDir.name);

             }

           while( _findnext( lfDir, &fileDir ) == 0 );// the common way to tranverse the files, and you can not get the number of files without tranversing files, which is different from matlab

        }

    _findclose(lfDir);  // still do not forget to close

    unsigned int i=fileDir.size;

    printf("%d\n",i);

    return 0;

}

 another method is that you can put all the file names to one txt files using system function, then you can access all the files one by one through reading this txt file.

#include <iostream>
#include  <string>
#include <fstream>
using namesapce std;
int main()
{
system("dir /a-d /b D:\\zhuanfa_singapore\\step_1\\*.* >D:\\zhuanfa_singapore\\step_2\\list.txt");
// all the file names under D:\\zhuanfa_singapore\\step_1 will be stored in
//D:\\zhuanfa_singapore\\step_2\\list.txt
my_in.open("D:\\zhuanfa_singapore\\step_2\\list.txt",ios::in);
string str2="D:\\zhuanfa_singapore\\step_1\\";
 while(!my_in.eof())
 {
     string str1;
     getline(my_in,str1);
     string str3=str2+str8;
     fstream _file;
     _file.open(str3.c_str(),ios::in);
       if(!_file)
      {
         cout<<str3<<"not exist!"<<endl;
      }
      else
      {
         cout<<str3<<"already exsit!"<<endl;

      }
 }
 my_in.close();
return 0;
}


C\C++ on linux seems a little different, i will record that in another post.