titbits from the world less travelled

Archive for the 'c++' Category

Adding a horizontal scrollbar to CListBox in windows

Description of Listbox:

Provides the functionality of a Windows list box.
Copy

class CListBox : public CWnd

Remarks

A list box displays a list of items, such as filenames, that the user can view and select.

In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window.

You can create a list box either from a dialog template or directly in your code. To create it directly, construct the CListBox object, then call the Create member function to create the Windows list-box control and attach it to the CListBox object. To use a list box in a dialog template, declare a list-box variable in your dialog box class, then use DDX_Control in your dialog box class’s DoDataExchange function to connect the member variable to the control. (this is done for you automatically when you add a control variable to your dialog box class.)

Its possible to go to the resource file and add your settings directly. See below:

LISTBOX LBS_SORT | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT | LBS_DISABLENOSCROLL | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP

But sometimes, this wont do the work. Even though you get the vertical scrollbar automatically, somehow the horizontal scrollbar refuses to show up. We need to use TEXTMETRIC and CDC to do that. We read the length of the input and adjust the width according to that:

TEXTMETRIC vartm; //contains information about the font

The CDC object provides member functions for working with a device context, such as a display or printer, as well as members for working with a display context associated with the client area of a window.

Do all drawing through the member functions of a CDC object. The class provides member functions for device-context operations, working with drawing tools, type-safe graphics device interface (GDI) object selection, and working with colors and palettes. It also provides member functions for getting and setting drawing attributes, mapping, working with the viewport, working with the window extent, converting coordinates, working with regions, clipping, drawing lines, and drawing simple shapes, ellipses, and polygons. Member functions are also provided for drawing text, working with fonts, using printer escapes, scrolling, and playing metafiles.

//varListbox is the variable name of CListBox
//you would need to call this inside the InitDialog of listbox, so that these changes are reflected in listbox

CDC* varDC = varListbox.GetDC();

if( varDC) //check for NULL
{
varDC ->GetTextMetrics(&varTM);
size_t sizeOfHz = varTM.tmAveCharWidth * 500; //you can replace 500 with any number you want
m_varListbox.SetHorizontalExtent(sizeOfHz );
//release CDC
}

posted by admin in c++, windows and have No Comments

Retrive the class names of all windows[MSDN]

Below search method will be useful when you need to find a window with no caption.

FindWindow will not work correctly in such a instance.

You can make use of the below method to do that.

//get the handle to the top window

HWND h = ::GetTopWindow(0);
while ( h)
{
TCHAR    buf[100];
::GetClassName( h, (LPTSTR)&buf, 100 );
if ( _tcscmp( buf, _T(“Youclassnametosearch”) ) == 0 )
return true;

//get the handle to the next window

h = ::GetNextWindow( h , GW_HWNDNEXT);

}
return false;

posted by admin in c++, windows and have No Comments

Making a .sis file for Nokia [download makesis and Comdlg32.ocx]

The easiest way to create a .sis file would be to use the tool makesis. You can download the tool from here:

http://www.kmdarshan.com/makesis/Makesis_v1.0_by_Gip.rar

http://www.kmdarshan.com/makesis/Makesis_v1.0.zip

Also you would need to download this dll, and put it in your C:\Windows\System32 for this tool to work. you can download the dll here:

http://www.kmdarshan.com/makesis/Comdlg32.zip

good luck packaging.

posted by admin in Qt, c++ and have No Comments

Using Qtimer instead of Sleep

Sample code to use Qtimer in Qt instead of Sleep if you want a stoppage in your code:

slideShowtimer = new QTimer(this);

        selectedPicture = 0;
        //QTimer::singleShot(5000, this, SLOT(slideShowHelper()));
        connect(slideShowtimer, SIGNAL(timeout()), this, SLOT(slideShowHelper()));
        slideShowtimer->start(1000);

 
                                 
            
posted by admin in Qt, c++ and have No Comments

Implementing simple multithreading in C++

Bare steps to implement multi threading in C++:

a. Declare a global variable, to hold the reference counts.

b. Declare CRITICAL SECTION

code:

CRITICAL_SECTION cs_test;
int loadCnt=0;

c. Now everytime you access the code you want to be protected when multiple threads access them

InitializeCriticalSection(&cs_test);
EnterCriticalSection(&cs_test);

if(loadCnt >0)
{
loadCnt++;
return
}else{

//your code here

}

LeaveCriticalSection(&cs_test);

return;

d. you could do the same for de initializing also.

e. But the best way to do the above is to implement them using class and objects.

posted by admin in c++ and have No Comments

Windows developer tools you need to have

Some tools which I really find helpful are:

a. Multimon – Support for multiple monitors

b. Process Monitor

c. Process Explorer

d. Desktops – Desktops allows you to organize your applications on up to four virtual desktops.

e. OleView – For COM purposes

f. Spy++ – For windows GUI handling

g. Resource hunter – Reading resource files. It will be helpful when your working on multiple languages.

posted by admin in c++, windows and have No Comments

Tip 1: Optimize code to run faster

1. Use constants with reference when passing values in between methods.

Advantage: It will reduce space and will be faster. If you use a new variable then an additional copy is made and there is a small memory hit.

Ex: method(string val)

optimal usage: method(const string &val)

Here we are passing the value by reference.

posted by admin in c++ and have No Comments

ACL: Denying read access to a file in VC++

Snippet of the code to set the permissions and create a file while not granting read access to it:

DWORD dwRes;
PSID pEveryoneSID = NULL, pAdminSID = NULL;
PACL pACL = NULL;
PSECURITY_DESCRIPTOR pSD = NULL;
EXPLICIT_ACCESS ea[2];
SID_IDENTIFIER_AUTHORITY SIDAuthWorld =
SECURITY_WORLD_SID_AUTHORITY;
SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY;
SECURITY_ATTRIBUTES sa;

// Create a well-known SID for the Everyone group.
if(!AllocateAndInitializeSid(&SIDAuthWorld, 1,
SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0,
&pEveryoneSID))
{
printf(“AllocateAndInitializeSid Error %u\n”, GetLastError());
goto Cleanup;
}

// Initialize an EXPLICIT_ACCESS structure for an ACE.
// The ACE will allow Everyone read access to the key.
ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS));
ea[0].grfAccessPermissions = KEY_READ;
ea[0].grfAccessMode = SET_ACCESS;
ea[0].grfInheritance= NO_INHERITANCE;
ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ea[0].Trustee.ptstrName = (LPTSTR) pEveryoneSID;

// Create a SID for the BUILTIN\Administrators group.
if(! AllocateAndInitializeSid(&SIDAuthNT, 2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&pAdminSID))
{
printf(“AllocateAndInitializeSid Error %u\n”, GetLastError());
goto Cleanup;
}

// Initialize an EXPLICIT_ACCESS structure for an ACE.
// The ACE will allow the Administrators group full access to
// the key.
ea[1].grfAccessPermissions = KEY_ALL_ACCESS;
ea[1].grfAccessMode = SET_ACCESS;
ea[1].grfInheritance= NO_INHERITANCE;
ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
ea[1].Trustee.ptstrName = (LPTSTR) pAdminSID;

// Create a new ACL that contains the new ACEs.
dwRes = SetEntriesInAcl(2, ea, NULL, &pACL);
if (ERROR_SUCCESS != dwRes)
{
printf(“SetEntriesInAcl Error %u\n”, GetLastError());
goto Cleanup;
}

// Initialize a security descriptor.
pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
SECURITY_DESCRIPTOR_MIN_LENGTH);
if (NULL == pSD)
{
printf(“LocalAlloc Error %u\n”, GetLastError());
goto Cleanup;
}

if (!InitializeSecurityDescriptor(pSD,
SECURITY_DESCRIPTOR_REVISION))
{
printf(“InitializeSecurityDescriptor Error %u\n”,
GetLastError());
goto Cleanup;
}

// Add the ACL to the security descriptor.
if (!SetSecurityDescriptorDacl(pSD,
TRUE, // bDaclPresent flag
pACL,
FALSE)) // not a default DACL
{
printf(“SetSecurityDescriptorDacl Error %u\n”,
GetLastError());
goto Cleanup;
}

// Initialize a security attributes structure.
sa.nLength = sizeof (SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = FALSE;

// Use the security attributes to set the security descriptor
// when you create a file.
HANDLE hFile = CreateFile( L”C:\\readAccessDenied.txt”,
GENERIC_READ,//FILE_READ_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE,
&sa,
CREATE_NEW,
0,
NULL );
CloseHandle(hFile);

Cleanup:

if (pEveryoneSID)
FreeSid(pEveryoneSID);
if (pAdminSID)
FreeSid(pAdminSID);
if (pACL)
LocalFree(pACL);
if (pSD)
LocalFree(pSD);

posted by admin in Testing, c++ and have No Comments

LUA : Method to split a string and output it into a array

First of all i need to give credit to www.wellho.net. I got some code from their website also to implement this.

My basic requirement was to read from the input arguments and display it as a vector of type integers.

Below is the code. Pardon me for the formatting issues. Wordpress sucks when coding:

function string:split(delimiter)
local result = { }
local from  = 1
local delim_from, delim_to = string.find( self, delimiter, from  )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from  = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from  )
end
table.insert( result, string.sub( self, from  ) )
return result
end

Then I call the below code from my main method:

have = string.split(inputArgs, “,” )
names= {};
for index,today in pairs(have) do
if today == “1″ then
names[index] = 1;
elseif today == “2″ then
names[index] = 2;
elseif today == “4″ then
names[index] = 4;
end
end

return names; //this returns the vector of integers

posted by admin in c++, lua, programming languages and have No Comments

Using CListBox in windows especially in pop up windows

I had an opportunity to use CListbox. The scenario was that I had to pre populate the list box and display it in a pop up window.

Its very to use listbox when using it in a parent window but when you want to display it in a standalone pop up window, you would get an error.

This is because the data is present only after the window comes into picture completely and is gone when the window disappears. In order to rectify this you would need to over rider the Initdialog method as below:

BOOL OnInitDialog()
{
//check if the parent window dialog is also initialized
if(CDialog::OnInitDialog())
{
//enter the values into the listbox here
}
}

By the above code you can enter into a listbox before its displayed.

Declare the below methods in the header file for getting the list selection changes:
afx_msg void OnLbnSelchangeList1();
afx_msg void OnLbnDblclkList1();

Add them to the message map in the class as below:

BEGIN_MESSAGE_MAP(YourClassname, CWnd)
ON_LBN_SELCHANGE(IDC_LIST1, &YourClassname::OnLbnSelchangeList1)
ON_LBN_DBLCLK(IDC_LIST1, &YourClassname::OnLbnDblclkList1)
END_MESSAGE_MAP()

Over ride them with the functionalities you need as below:
void YourClassname::OnLbnSelchangeList1()
{

}

void YourClassname::OnLbnDblclkList1()
{
// TODO: Add your control notification handler code here
}

Use CArray to get the values:

CArray aryListBoxSel;
aryListBoxSel.SetSize(nCurrentSelected);
m_ListBox1.GetSelItems(nCurrentSelected, aryListBoxSel.GetData());
CString sTitle;
int indexVal = 0;

for(int i=0;i<=aryListBoxSel.GetUpperBound();i++)
{
indexVal = aryListBoxSel.GetAt(i);
m_ListBox1.GetText(indexVal, sTitle);
}
---------------------------------------------------------------------------------------------------
Incase CArray gives a error in vc6 you can do the following:

int Count = m_ListBox1.GetSelCount();
if (Count > 0)
{
int *pSels = new int[Count];
m_ListBox1.GetSelItems(Count,pSels);
for (int i = 0; i < Count;i++)
{
//pSels[i] this is the index of the item that was selected
CString Temp;
m_ListBox1.GetText(pSels[i],Temp);
}
delete [] pSels;
}

posted by admin in c++, msdn, visual studio, windows and have No Comments