Monday, May 28, 2007

MFC Temporary Handles

If we want a CWnd object from  a hwnd , the first functions coming to my mind is these.
CWnd -> Attach()
or
CWnd::FromHandle().


The difference is this , the CWnd::FromHandle first checks if the specified hwnd is already in the Permenent handle map. If so it
returns the CWnd * from the map. If it can't find it searches in the Temporary map and returns. if it couldn't see the hwnd in both
permenent and temporary map it will create a new CWnd * object and add it to temporary map.


So the point is this. The temporary objects are deleted during the idle time. So don't store the pointer returned from CWnd::FromHandle like functions ( CPen, CDC , CGDIObject etc ).


If we are calling Attach. it should be detached, otherwise during the destruction of the class (CWnd), the destructor calls the ::DestroyWindow API , to destroy the attached window( may be we don't want to do that). Also don't give non-MFC window pointer to Attach function. It is not valid . If you want , then use FromHandle function

Monday, May 14, 2007

A Easy message filter to a Win32 application vc++.

IF you know c# or vc.Net you can see interfaces like IMessageFilter , which allows to filter a particular message from the application.

So this can be done in win32 with some lines of coding , no need for any interface :)).
I don't want to explain anything more than these code snippets.We know every win32 app has a message loop. it may be look like this

while(GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
   TranslateMessage(&msg);
   DispatchMessage(&msg);
}
}

So we can add filter , which will filter all WM_LBUTTONDOWN message from this application by a mere checking, like
while (GetMessage(&msg, NULL, 0, 0))
{
 if (msg.message != WM_LBUTTONDOWN && !TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
 {
   TranslateMessage(&msg);
   DispatchMessage(&msg);
  }
}

Thats all.. 

Friday, May 11, 2007

Why ++i is faster than i++

 
Why ++i is faster than i++. Are you ever heard meaning less
discussions like "which is More Fast i++ or  ++ i"? or ++j or j++ or ++k or k++ . hahahaha.  


IF you are serious I can say it will depends upon what is this i and j. If these variables are mere integers it
doesn't matter. We can use both. Both of them are of same speed. Then Problem is with floating point? Or double?.. No noo.. :). Actually there is no problem for ++i or i++.



The problem comes when people do
coding without concentration. Let us look the following example.



class COperator
{
    int i;

public:
    COperator(){i= 0;}
    COperator&
    operator ++()
    {
       i++;
       return
       *this;
     }
     COperator operator ++(int)
     {
        COperator temp = *this;
        i++;
        return temp;
     }

};



In an expression as shown in below ,

COperator
it; // now i =0
it++; //
now i is 1
COperator
pt = it++; //now pt.i = 1 & it.i = 2;



Here for preserving the behaviour of original posix operator(I++), there is a
need for creating the temporary object in the stack((look operator ++(int) ) ,
and we return the temporary object.


So the point is this , some times in loops we often use i++ than ++i. It is a style.
Ok , but is good with integers(etc). But in case of class the obj++ will create
a extra object in stack and there is also a copy operation
. Since in loops
we need is a just an increment (or something like that). That’s why it is
prefered to use ++it rather than I++. If you ever programmed with STL you can
see that STL list uses iterators. They are class objects. So in that iterating
loops use ++it rather than it++. This will save some computing time and memory.

Tuesday, May 8, 2007

OpenMP with Vc++

Microsoft Windows provides support for OpenMP standard. If you don't know what is OpenMP read this from wikipedia.

 " The OpenMP (Open Multi-Processing) is an application programming interface (API) that supports multi-platform shared memory multiprocessing programming in C/C++ and Fortran on many architectures, including Unix and Microsoft Windows platforms. It consists of a set of compiler directives, library routines, and environment variables that influence run-time behavior."

 In VC++ this OpenMP can be called using #pragma omp <> directvies.
 OpeMP is mainly used for parellel computing in the applications. Thread is created in openMp is like this
#pragma omp parallel num_threads(count ) , So the codes after this directive will be excuted in separte threads. count is the thread count.


For example
 #pragma omp parallel num_threads(3)
{
    ::MessageBox(0,_T("Threads"),0,0);
}


Here we can see 3 different message box while the running this program. it is not possible to "return" or "goto" from inside the omp blocks.
Another example is parallely computing the sum of numbers in an array. Like this


int arry[10] = {1,2,3,4,5,6,7,8,9,10};
#pragma omp parallel for


for(int i = 0; i < 10;i++)
{
    sum+=arry[i];
}

Note:  For using OpenMp in you application , you should provide the switch /openmp in compiler options.
          If you need more information about OpenMp , please look the following links
         1 . http://en.wikipedia.org/wiki/OpenMP
         2.http://developers.sun.com/sunstudio/articles/omp-intro.html

Monday, May 7, 2007

Calculation using templates c++.

C++ Templates can also be used to evaluate an expression. Here i am just putting an example ( got from internet , and is working).
This template class can be used to find the factorial of a number. Actually the compiler calculates the factorial at compile time , during the template parsing.


template <int T>
class Factorial
{
public :
   // Recursive definition
   enum { GetValue = T * Factorial<T-1>::GetValue };
};


// specialization.
template <>
class Factorial<1>
{
public :
    enum { GetValue = 1 };


};

we can find the factorial using the class Factorial. For example Factorial<5>::GetValue will give the factorial of 5. Factorial of 1 is handled as a special way (Just to exit) . So the code may look like this

int fact = Factorial<5>::GetValue;

If you try to find the factorial of 0 the visual studio will crash , Not the application :), because the factorial is computed by the compiler.Because if we put zero, there is no way to exit the compilation process (check with above codes). So you may need to handle 0 as a special case. or change the specialization to Factorial<0>

Note : Use of this feature will cause to slow down the compiling process.

Easy way to Disable IME window in an Win32 Application

In this world of Unicode still we often do non Unicode applications. But there is a feature in windows operating system it allows to enter Unicode characters or characters other than basic ascii character set to our application.So What happens is when user press enter key these unicode characters will turn to "????" .Because our application is non Unicode .

So there is a easy way to disappear this IME window when our application comes to front. Microsoft provides api like

1 ImmDisableIme
2 ImmAssociateContext

So if you want to make disappear the ime window for a particular window in you application , you can use ImmAssociateContext.

like ImmAssociateContext(YourHwnd,0) , If don't wan to use the ime feature at all use ImmDisableIme().

The ImmDisableIme will cause to disable IME for all windows in you application .One important thing you should call this function , before any window is created.
Like ImmDisableIme( GetCurrentThreadID()). For an mfc application the best place to call is from CYourApp::InitInstance() , where CYourApp derived from CWinApp.



Wednesday, May 2, 2007

goto and static.

I don't want nothing much to write here except the following code sequence.Can anyone predict the outout???

int _tmain(int argc, _TCHAR* argv[])

{

goto XXX;

static int u = 90;


XXX:

printf("%d",u);

return 0;

}


It is 90 , that is the variable u getting the value 90. How the u gets this value ? .Eventough there is a goto before the assignent statement.

If you debug the following code you can see that the control never goes to the line "static test u = 90;" .Oho god how this happens???.

I think the compiler will handle the static variables while on the program loading. Because compiler need to reserve memory for a static variable whether it is declared in local function or global , it doesn't matter. Thats how here the variable u gets the value 90. if it is not a static variable the the program crashes without asking anybody.


If you try the same code replacing integer u with a some class object , like



class test
{


public :
  int val;
  test() 
  {
    val = 90;
   }


};




int _tmain(int argc, _TCHAR* argv[])
{

goto XXX;
static test u;
XXX:
printf("%d",u.val);


return 0;

}


you will never get the value 90 as output. Because the construcor is not called by the compiler eventhough it is static object.


So summarizing the facts , it will be like this.


1. static varibles memory allocation happens in anycase.
2. compiler also saves the value to the varible in statement like static int s = 90;
3 If you have class and it has a constructor accepting an integer , you can write like

static MyClass obj = 90; (But it will not get called ever, in our case)

Any comments , welcome!!!.

Note : I have tried the above test with VS2005 only. This behavior is compiler dependent.