Archive

Author Archive

Windows Privileges Issues !!

October 21, 2009 BijU Leave a comment
A very interesting tip..
For my current project, I need to set the system time with some reference time. Quite easy!!. The SetSytemTime (). The syntax is like this
BOOL WINAPI SetSystemTime(
__in          const SYSTEMTIME* lpSystemTime
);
The time must be in the form of SYSTEMTIME struct.  And I implement it in my code as
SYSTEMTIME st = NewTime;
bSuccess = SetSystemTime(&st);
:) . The problem is on the way.
The SetSystemTime function enables the SE_SYSTEMTIME_NAME privilege before changing the system time. This privilege is disabled by default. (©MSDN)
for changing the privileges, we need to implement some authorization functions. In the following order
1-  OpenProcessToken() – opens the access token associated with a process
2-  LookupPrivilegeValue() – Retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name
3-   AdjustTokenPrivileges()-enables or disables privileges in the specified access token.
After that, change the system time with SetSystemTime() method.
Then again reset the privileges by using the function AdjustTokenPrivileges().
It works well in WindowsXP. No problems for setting the new time.  J
But , the problem comes from Windows 7 and Windows Vista.
Then, I start debugging my code in Windows 7. All authorization functions works fine for me.  Like OpenProcessToken(),LookupPrivilegeValue() and AdjustTokenPrivileges(). But I felt something bad about the execution of the last method. AdjustTokenPrivileges()..
I checked the GetLastError() return value. Instead of ERROR_SUCCESS
, it returns ERROR_NOT_ALL_ASSIGNED J
So my investigation is now in that way. How to handle that? Its all because of UAC (User Access Control) problems. Because the SE_SYSTEMTIME_NAME require administrative privilege.
My colleague gave me a tip about Manifests.
The description from MSDN is like Manifests are XML files that accompany and describe side-by-side assemblies or isolated applications. Manifests uniquely identify the assembly through the assembly’s <assemblyIdentity> element. They contain information used for binding and activation, such as COM classes, interfaces, and type libraries, that has traditionally been stored in the registry. Manifests also specify the files that make up the assembly and may include Windows classes if the assembly author wants them to be versioned. Side-by-side assemblies are not registered on the system, but are available to applications and other assemblies on the system that specify dependencies in manifest files.
Manifest files enable administrators and applications to manage side-by-side assembly versions after deployment. Every side-by-side assembly must have a manifest associated with it. The installation of Windows XP installs the supported Microsoft side-by-side assemblies with their manifests. If you develop your own side-by-side assemblies, you must also install manifest files
I turn on the manifests for my application also. Its very simple.
Project Settings > Linker > Manifest File.
And make the options as indicated in the figure.
Including manifest for project
The Rebuild All  and Execute..
:)
for http://vctipsplusplus.wordpress.com/
BijU
Gravity is not responsible for people to fall in love. It just happens.

A very interesting tip..

For my current project, I need to set the system time with some reference time. Quite easy!!. Using SetSytemTime (). The syntax is like this

BOOL WINAPI SetSystemTime(

__in          const SYSTEMTIME* lpSystemTime

);

The time must be in the form of SYSTEMTIME struct.  And I implement it in my code as

SYSTEMTIME st = NewTime;

bSuccess = SetSystemTime(&st);

:) . The problem is on the way.

The SetSystemTime function enables the SE_SYSTEMTIME_NAME privilege before changing the system time. This privilege is disabled by default. (©MSDN)

for changing the privileges, we need to implement some authorization functions. In the following order

1-  OpenProcessToken() – opens the access token associated with a process

2-  LookupPrivilegeValue() – Retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name

3-   AdjustTokenPrivileges()-enables or disables privileges in the specified access token.

After that, change the system time with SetSystemTime() method.

Then again reset the privileges by using the function AdjustTokenPrivileges().

It works well in WindowsXP. No problems for setting the new time.  :) But , the problem comes from Windows 7 and Windows Vista.

Then, I start debugging my code in Windows 7. All authorization functions works fine for me.  Like OpenProcessToken(),LookupPrivilegeValue() and AdjustTokenPrivileges(). But I felt something bad about the execution of the last method. AdjustTokenPrivileges()..

I checked the GetLastError() return value. Instead of ERROR_SUCCESS, it returns ERROR_NOT_ALL_ASSIGNED J

So my investigation is now in that way. How to handle that? Its all because of UAC (User Access Control) problems. Because the SE_SYSTEMTIME_NAME require administrative privilege.

My colleague gave me a tip about Manifests.

The description from MSDN is like Manifests are XML files that accompany and describe side-by-side assemblies or isolated applications. Manifests uniquely identify the assembly through the assembly’s <assemblyIdentity> element. They contain information used for binding and activation, such as COM classes, interfaces, and type libraries, that has traditionally been stored in the registry. Manifests also specify the files that make up the assembly and may include Windows classes if the assembly author wants them to be versioned. Side-by-side assemblies are not registered on the system, but are available to applications and other assemblies on the system that specify dependencies in manifest files.

Manifest files enable administrators and applications to manage side-by-side assembly versions after deployment. Every side-by-side assembly must have a manifest associated with it. The installation of Windows XP installs the supported Microsoft side-by-side assemblies with their manifests. If you develop your own side-by-side assemblies, you must also install manifest files

I turn on the manifests for my application also. Its very simple.

Project Settings > Linker > Manifest File. And make the options as indicated in the figure.

Project Settings>Linker Options > Manifest

Project Settings>Linker Options > Manifest

Including manifest for project

The Rebuild All  and Execute..

:)

for http://vctipsplusplus.wordpress.com/

BijU

Gravity is not responsible for people to fall in love. It just happens.

Categories: Visual C++

Environment Varaibles using VC++

October 20, 2009 BijU Leave a comment

Environment variable are variables that can be available to all running programs.  You can access the environment variables using Control Panel > System > Advanced > Environment Variables (Lot of other methods are also available :) )

Environment Variables

Environment Variables

Environment Variables

Environment Variables

In Windows Registry, you can locate them on HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ Control\ Session Manager\ Environment.

Some of the Environment Variables are TEMP, TMP, OS etc.

A number of situations may come during the coding phase to access those variables. For eg: getting the temp folder name, system folder name, lib path, include path etc.

We can access those items from environment variables using the following commands.

ExpandEnvironmentStrings()  - function expands environment-variable strings and replaces them with their defined values.

and ExpandEnvironmentStringsForUser()-function expands the source string by using the environment block established for the specified user.

Like this

CString strErrorMsg = _T(“”);

TCHAR szEnvPath[MAX_PATH];

DWORD dwLen = 0;

dwLen = ::ExpandEnvironmentStrings( _T(“%MSDevDir%”), szEnvPath, MAX_PATH );

if( 0 == dwLen)

{

// ExpandEnvironmentStrings() failed

strErrorMsg = _T(“Cannot Expand using ExpandEnvironmentStrings()”);

}

Now the value for the MSDevDir is in the szEnvPath variable. :)

for http://vctipsplusplus.wordpress.com/

BijU

Every day you waste is one you can never make up

Categories: Visual C++

Turn Off your Monitor Display !!

October 15, 2009 BijU Leave a comment

On Off Switch

Image Source: http://thumbs.dreamstime.com/thumb_76/1154983417etR5O8.jpg

Nowadays, I’m experimenting with some hardware and Windows :) .I’m very happy to work with this. Because, after a lot of reading and googling, doing some coding. Then again, reading a lot of documents :)

A very interesting thing in doing this type of coding is that, we don’t get  much information from MSDN :D . Almost all information is available in the MSDN, but it’s up to you to find the best algorithm/class/technology that fit for you.

Yesterday, I tried a lot to get the information from our Desktop Monitor. My aim was to ON/OFF our Desktop Monitor. I have hands on experience with WMI (Windows Management Instrumentation) to query the details like motherboard, disks, Operating System etc. With that confidence I first look into the Win32_DesktopMonitor. And in that a method named SetPowerState() is available. And the information about that method give me immense pleasure.

Its like “The SetPowerState method sets the desired power state for a logical device and when a device should be put into that state. And the power state may have the following values, like(from MSDN)

1 Full power.
2 Power save — low-power mode.
3 Power save — standby.
4 Power save — other.
5 Power cycle.
6 Power off.

I’m very happy after reading this document.  Unfortunately, its not implemented by windows. Due to a lot of technical problems.

So..

But using the very common message like SendMessage can solve the problem so easily.

Just copy the below statement and execute..

SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM)2);

Hope you are familiar with first 2 params. Documentation from the  MSDN for the 3rd param is

SC_MONITORPOWER Sets the state of the display. This command supports devices that have power-saving features, such as a battery-powered personal computer.

And the 4th param may take the values like

-1 – the display is being on

1 – the display is going to low power

2 – the display is being shut off

I think it is so simple. Thanks to Microsoft.. :)

for http://vctipsplusplus.wordpress.com/

BijU

God won’t ask about the fancy clothes in your wardrobe, but will ask how many of those clothes helped the needy.

Categories: Visual C++

String Conversion..

August 12, 2009 BijU 1 comment
A very nice section under windows programming..
Every windows programmer may deals with UNICODE, ANSI like character encoding schemes..
And also, the conversion from Unicode to ANSI and vice versa..
Now I collect some stuffs for you..
Converting UNICODE string to ANSI strings..
You can convert a Unicode string to an ANSI string with the WideCharToMultiByte() API
The syntax is
int WideCharToMultiByte(
UINT CodePage,
DWORD dwFlags,
LPCWSTR lpWideCharStr,
int cchWideChar,
LPSTR lpMultiByteStr,
int cbMultiByte,
LPCSTR lpDefaultChar,
LPBOOL lpUsedDefaultChar
);
For example, we have our UNICODE string in wszUNICODEString, we want to convert that to ANSI string szANSIString.
char szANSIString [MAX_PATH];
WideCharToMultiByte ( CP_ACP,                // ANSI code page
WC_COMPOSITECHECK,     // Check for accented characters
wszUNICODEString,         // Source Unicode string
-1,                    // -1 means string is zero-terminated
szANSIString,          // Destination char string
sizeof(szANSIString),  // Size of buffer
NULL,                  // No default character
NULL );                // Don’t care about this flag
wcstombs()
Converts a sequence of wide characters to a corresponding sequence of multibyte characters.
Syntax is just
size_t wcstombs_s(
char *mbstr,
const wchar_t *wcstr,
size_t count
);
For eg:  wcstombs_s ( szANSIString, wszUNICODEString, sizeof(szANSIString) );
CString
Using CString class’s constructors and assignment  operators, we can convert UNICODE string to ANSI string.
Using constructor
CString strANSI_1 (wszUNICODEString);
Using Assignment Operator
CString strANSI_2;
strANSI_2 = wszUNICODEString;
ATL macros
To convert a Unicode string to ANSI, use the W2A() macro
#include <atlconv.h>
….
{
char szANSIString [MAX_PATH];
USES_CONVERSION;  // DeclareA very nice section under windows programming..
Every windows programmer may deals with UNICODE, ANSI like character encoding schemes..
And also, the conversion from Unicode to ANSI and vice versa..
Now I collect some stuffs for you..
Converting UNICODE string to ANSI strings..
You can convert a Unicode string to an ANSI string with the WideCharToMultiByte() API
The syntax is
int WideCharToMultiByte(
UINT CodePage,
DWORD dwFlags,
LPCWSTR lpWideCharStr,
int cchWideChar,
LPSTR lpMultiByteStr,
int cbMultiByte,
LPCSTR lpDefaultChar,
LPBOOL lpUsedDefaultChar
);
For example, we have our UNICODE string in wszUNICODEString, we want to convert that to ANSI string szANSIString.
char szANSIString [MAX_PATH];
WideCharToMultiByte ( CP_ACP,                // ANSI code page
WC_COMPOSITECHECK,     // Check for accented characters
wszUNICODEString,         // Source Unicode string
-1,                    // -1 means string is zero-terminated
szANSIString,          // Destination char string
sizeof(szANSIString),  // Size of buffer
NULL,                  // No default character
NULL );                // Don’t care about this flag
wcstombs()
Converts a sequence of wide characters to a corresponding sequence of multibyte characters.
Syntax is just
size_t wcstombs_s(
char *mbstr,
const wchar_t *wcstr,
size_t count
);
For eg:  wcstombs_s ( szANSIString, wszUNICODEString, sizeof(szANSIString) );
CString
Using CString class’s constructors and assignment  operators, we can convert UNICODE string to ANSI string.
Using constructor
CString strANSI_1 (wszUNICODEString);
Using Assignment Operator
CString strANSI_2;
strANSI_2 = wszUNICODEString;
ATL macros
To convert a Unicode string to ANSI, use the W2A() macro
#include <atlconv.h>
….
{
char szANSIString [MAX_PATH];
USES_CONVERSION;  // Declare local variable used by the macros.
lstrcpy ( szANSIString, W2A (wszUNICODEString) );
}
For every coin there is an another side also..
local variable used by the macros.
lstrcpy ( szANSIString, W2A (wszUNICODEString) );
}
For every coin there is an another side also..

A very nice section under windows programming..

Every windows programmer may deals with UNICODE, ANSI like character encoding schemes..

And also, the conversion from Unicode to ANSI and vice versa..

Now I collect some stuffs for you..

Converting UNICODE string to ANSI strings..

You can convert a Unicode string to an ANSI string with the WideCharToMultiByte() API

The syntax is

int WideCharToMultiByte(
  UINT CodePage, 
  DWORD dwFlags, 
  LPCWSTR lpWideCharStr,
  int cchWideChar, 
  LPSTR lpMultiByteStr, 
  int cbMultiByte,
  LPCSTR lpDefaultChar,    
  LPBOOL lpUsedDefaultChar
);

For example, we have our UNICODE string in wszUNICODEString, we want to convert that to ANSI string szANSIString.

char szANSIString [MAX_PATH];
 WideCharToMultiByte ( CP_ACP,                // ANSI code page
                          WC_COMPOSITECHECK,     // Check for accented characters
                          wszUNICODEString,         // Source Unicode string
                          -1,                    // -1 means string is zero-terminated
                          szANSIString,          // Destination char string
                          sizeof(szANSIString),  // Size of buffer
                          NULL,                  // No default character
                          NULL );                // Don't care about this flag

wcstombs()

Converts a sequence of wide characters to a corresponding sequence of multibyte characters.

Syntax is just

size_t wcstombs_s(
   char *mbstr,
   const wchar_t *wcstr,
   size_t count 
);

For eg:

 wcstombs_s ( szANSIString, wszUNICODEString, sizeof(szANSIString) );

CString

Using CString class’s constructors and assignment  operators, we can convert UNICODE string to ANSI string.

Using constructor:

CString strANSI_1 (wszUNICODEString);

Using Assignment Operator

CString strANSI_2;
strANSI_2 = wszUNICODEString;

ATL macros

To convert a Unicode string to ANSI, use the W2A() macro

#include <atlconv.h>
….
{
char szANSIString [MAX_PATH];
USES_CONVERSION;  // Declare local variable used by the macros.
    lstrcpy ( szANSIString, W2A (wszUNICODEString) );
}

for http://vctipsplusplus.wordpress.com/

BijU

Make the best of lifes moments !!

What really matters at the end of the day is if you made the best use of time,
and done everything that you needed to do.

Don’t sit just there waiting, You only live once!

Categories: Visual C++

How To Know the MFC version you are using..

July 14, 2009 BijU Leave a comment

Hi all,

Do you know, how to get  information about, the MFC version we are using?

Please follow these steps:

1. Locate the file afxver_.h (It is in the folder  ”include”)

2. Check the value of symbolic constant  _MFC_VER

3. :) That value is the MFC version number…

for eg:

#define _MFC_VER 0×0800 // Microsoft Foundation Classes version 8.00

for http://vctipsplusplus.wordpress.com/

BijU

When you’re in great distress,
call for God’s help from the very core of your heart.
Be sincere, Pray fervently.
You will get His help.

Categories: How To Know

RegDllView.. A nice utility

July 10, 2009 BijU Leave a comment

Hi all,

Today i’m talking about a nice utility, that I found during my googling.

RegDllView

It is a very simple and is very useful for all Windows programmers. During the development/unit testing/debugging of various types of DLLs, it is very useful tool.

RegDllView is a small utility that displays the list of all registered dll/ocx/exe files (COM registration). For each registered file, you can view the last date/time that it was registered, and the list of all registration entries (CLSID/ProgID).
RegDllView also allows you to unregister dll/ocx files that you don’t need on your system anymore. If you have dll/ocx files that don’t exist on your system anymore, but their registration entries are still exist in your Registry, you can manually remove these entries by using ‘Delete All Entries For Selected Files’ option.

regdllview

You can download the same from http://www.nirsoft.net/utils/regdllview.zip

for http://vctipsplusplus.wordpress.com/

BijU

Categories: Visual C++

My Marriage Invitation

April 30, 2009 BijU Leave a comment

Invitation Card

Categories: Visual C++

Different Image Conversion Techniques

April 8, 2009 BijU Leave a comment

Well, so many image formats are available in the world. Like BMP (Bitmap),TIFF (Tagged Image File Format ), JPG/JPEG (Joint Photographic Experts Group),GIF (Graphic Interchange Format),PNG (Portable Network Graphics) etc.

I already mentioned that, my current multimedia project gave me a lot of chance to improve my coding practice as well as to learn a lot of new things, like GDI,GDI+,Cryptographic services etc.

One of the requirement for me was to “Convert images between different formats”. Nice requirement :)

And I’m  in bloody confident that, I can complete my work within a day. And I started my job. But…..:(

I searched MSDN and found IPicture, (Nice COM). By using that, I load the image,resized the image, cropped, etc.. Then the main requirement is in front of the curtain. “Image conversion.” and I use the IPicture::SaveAsFile(). Then only i noticed the method thoroughly. “Saves the picture’s data into a stream in the same format that it would save itself into a file. Bitmaps use the BMP file format, metafiles the WMF format, and icons the ICO format “

So again google the keyword..

Then one of my friend suggested this page.. :)

Converting a BMP Image to a PNG Image http://msdn.microsoft.com/en-us/library/ms533837(VS.85).aspx

A very simple and nice article. by using that, we can convert the images between different formats.

code from MSDN

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
   UINT  num = 0;          // number of image encoders
   UINT  size = 0;         // size of the image encoder array in bytes

   ImageCodecInfo* pImageCodecInfo = NULL;

   GetImageEncodersSize(&num, &size);
   if(size == 0)
      return -1;  // Failure

   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
   if(pImageCodecInfo == NULL)
      return -1;  // Failure

   GetImageEncoders(num, size, pImageCodecInfo);

   for(UINT j = 0; j < num; ++j)
   {
      if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
      {
         *pClsid = pImageCodecInfo[j].Clsid;
         free(pImageCodecInfo);
         return j;  // Success
      }
   }

   free(pImageCodecInfo);
   return -1;  // Failure
}

INT main()

{

   // Initialize GDI+.

   GdiplusStartupInput gdiplusStartupInput;

   ULONG_PTR gdiplusToken;

   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   CLSID   encoderClsid;

   Status  stat;

   Image*   image = new Image(L”Bird.bmp”);

   // Get the CLSID of the PNG encoder.

   GetEncoderClsid(L”image/png”, &encoderClsid);

   stat = image->Save(L”Bird.png”, &encoderClsid, NULL);

   if(stat == Ok)

      printf(“Bird.png was saved successfully\n”);

   else

      printf(“Failure: stat = %d\n”, stat);

   delete image;

   GdiplusShutdown(gdiplusToken);

   return 0;

}

 

For retrieving the Class Identifier for an Encoder we can use the following formats.

  • image/bmp
  • image/jpeg
  • image/gif
  • image/tiff
  • image/png

So again curtain…

 

If you want to cross the sea, you have to step into the waves..

At first, the waves may distract you;

But gradually, you will subdue the fear within you.

For, no wave is mightier than the power of your mind.

 

for http://vctipsplusplus.wordpress.com/

BijU

Categories: Visual C++

Changing the background color of window created with CreatewindowEx()

February 4, 2009 BijU Leave a comment

Recently, I wanted to create a window using Win32. That was the first time, i created a window with Win32 :)

I successfully created the Window using CreateWindowEx(..).  The visaul appearance is same as MFC Dialog. 

Alas !! I faced one simple but serious problem. My Window looks white.

white1

I couldn’t change the background color.. :( … I tried a lot with the params and styles of CreateWindow(). Ooops.. :(

After that, I just go throgh Win32 documentation..hey one flag is there in the WNDCLASS structure.

xxxx.hbrBackground = (HBRUSH)GetSysColorBrush(COLOR_3DFACE);

:)

Now.. just look at my window.. Its pretty good na !!!

dlg

:)

Believe only what you see, what you test and judge to be true.

for http://vctipsplusplus.wordpress.com/

BijU

Categories: Visual C++

Creating Folders/Directories Made Simple

January 13, 2009 BijU 1 comment

image

I got this thread from one of my senior, while discussing about our project. Till then, I didn’t noticed any differences between SHCreateDirectoryEx() and CreateDirectory(). But now.. Yes its is.. some .. lil difference is there.

just look at the function call

for eg:

if (CreateDirectory(“c:\\Test\\Test\\Test\\Test”,NULL))
        AfxMessageBox(“Created “);

if (ERROR_SUCCESS == SHCreateDirectoryEx(NULL,”c:\\Test\\Test\\Test\\Test”,NULL))
{
    AfxMessageBox(“Created”);
}

description from MSDN is like that for SHCreateDirectoryEX()

int SHCreateDirectoryEx(HWND hwnd, LPCTSTR pszPath, SECURITY_ATTRIBUTES *psa);

BOOL CreateDirectory(LPCTSTR lpPathName,LPSECURITY_ATTRIBUTES lpSecurityAttributes );

This function creates a file system folder whose fully qualified path is given by pszPath. If one or more of the intermediate folders do not exist, they will be created as well.

for CreateDirectory() the description is like this “ This function creates a new directory”

 

Hope now you noticed the difference from the description itself. :)

 

 

True commitment begins when we decide to do it anyway.

for http://vctipsplusplus.wordpress.com/

BijU

:)

Categories: Visual C++