Sunday, January 21, 2018

Read arbitary bits

#define READ_VALUE(n, p, i) ((n) >> (p)) & ((1 <<(i)) - 1)

The above macro return the byes of specified position

Tuesday, March 19, 2013

Read XML using C++


Using this class you can read tag and value of a XML file and add the values in to a std::list.



//ReadXML.h

#include
#include
#include
#include
#import rename_namespace(_T("MSXML"))

class CReadXML
{
public:
CReadXML();
~CReadXML();
HRESULT CreateAndInitDOM(IXMLDOMDocument **ppDoc);
HRESULT VariantFromString(PCWSTR wszValue, VARIANT &Variant);
void LoadDOM( std::string pFileName, std::list>& values );
std::wstring String2WS (const std::string& s);
std::string ConvertWCSToMBS(const wchar_t* pstr, long wslen);
std::string ConvertBSTRToString(BSTR bstr);
BOOL CheckSubNodes( IXMLDOMNode *pNode );
void ReadNodeValues( IXMLDOMNode *pNode, std::list>& values );
void ReadSubNode( IXMLDOMNode *pNode, std::list>& values );

};


//ReadXML.cpp

#include
#include "ReadXML.h"
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms765465(v=vs.85).aspx

// Macro to verify memory allcation.
#define CHK_ALLOC(p)        do { if (!(p)) { hr = E_OUTOFMEMORY; goto CleanUp; } } while(0)

// Macro that calls a COM method returning HRESULT value.
#define CHK_HR(stmt)        do { hr=(stmt); if (FAILED(hr)) goto CleanUp; } while(0)

// Macro that releases a COM object if not NULL.
#define SAFE_RELEASE(p)     do { if ((p)) { (p)->Release(); (p) = NULL; } } while(0)


CReadXML::CReadXML()
{

}

CReadXML::~CReadXML()
{

}

// Helper function to create a DOM instance.
HRESULT CReadXML::CreateAndInitDOM(IXMLDOMDocument **ppDoc)
{

HRESULT hr = CoCreateInstance( __uuidof(MSXML::DOMDocument30), NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)ppDoc);
if (SUCCEEDED(hr))
{
// these methods should not fail so don't inspect result
(*ppDoc)->put_async(VARIANT_FALSE);
(*ppDoc)->put_validateOnParse(VARIANT_FALSE);
(*ppDoc)->put_resolveExternals(VARIANT_FALSE);
}
return hr;

//NOT WORKING, IF "xmlns=" IS IN XML FILE
//HRESULT hr = CoCreateInstance(__uuidof(MSXML::DOMDocument60), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(ppDoc));
//   if (SUCCEEDED(hr))
//   {
//       // these methods should not fail so don't inspect result
//       (*ppDoc)->put_async(VARIANT_FALSE);
//       (*ppDoc)->put_validateOnParse(VARIANT_FALSE);
//       (*ppDoc)->put_resolveExternals(VARIANT_FALSE);
//   }


}

// Helper function to create a VT_BSTR variant from a null terminated string.
HRESULT CReadXML::VariantFromString(PCWSTR wszValue, VARIANT &Variant)
{
HRESULT hr = S_OK;
BSTR bstr = SysAllocString(wszValue);
CHK_ALLOC(bstr);

V_VT(&Variant)   = VT_BSTR;
V_BSTR(&Variant) = bstr;

CleanUp:
return hr;
}

std::wstring CReadXML::String2WS (const std::string& s)
{
       std::wstringstream ws;

ws << s.c_str();
std::wstring sLogLevel = ws.str();
return sLogLevel;


// std::wstring ws;
//ws.assign (s.begin (), s.end ());
// return ws;
}

std::string CReadXML::ConvertWCSToMBS(const wchar_t* pstr, long wslen)
{
    int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL);

    std::string dblstr(len, '?');
    len = ::WideCharToMultiByte(CP_ACP, 0 /* no flags */,
                                pstr, wslen /* not necessary NULL-terminated */,
                                &dblstr[0], len,
                                NULL, NULL /* no default char */);

    return dblstr;
}

std::string CReadXML::ConvertBSTRToString(BSTR bstr)
{
    int wslen = ::SysStringLen(bstr);
    return ConvertWCSToMBS((wchar_t*)bstr, wslen);
}

void CReadXML::LoadDOM( std::string pFileName, std::list>& values )
{
HRESULT hr = S_OK;

IXMLDOMDocument *pXMLDom = NULL;
IXMLDOMParseError *pXMLErr = NULL;
IXMLDOMNodeList *NodeList = NULL;
IXMLDOMNode *pNode = NULL;

std::wstring wspFileName;

BSTR bstrXML = NULL;
BSTR bstrErr = NULL;
BSTR bstrQuery2 = NULL;

VARIANT_BOOL varStatus;
VARIANT varFileName;
VariantInit(&varFileName);

//Initialize COM Library:
CoInitialize(NULL);

CHK_HR(CreateAndInitDOM(&pXMLDom));  

wspFileName = String2WS(pFileName);

// XML file name to load
CHK_HR(VariantFromString( wspFileName.c_str(), varFileName));

CHK_HR(pXMLDom->load(varFileName, &varStatus));

if (varStatus == VARIANT_TRUE)
{
CHK_HR(pXMLDom->get_xml(&bstrXML));
//printf("XML DOM loaded from stocks.xml:\n%S\n", bstrXML);

bstrQuery2 = SysAllocString(L"Object"); // For find the tag Object.  Please replace this with your tag name.  If you need to read all values, then replace "Object" with " ".  But the problem is that, then each tags consider as each item, can not separate the child nodes.  For a better out put specify the tag name, where you want to start.

CHK_ALLOC(bstrQuery2);
CHK_HR(pXMLDom->getElementsByTagName(bstrQuery2, &NodeList));

if(NodeList)
{
//get the length of node-set
long length = 0;
CHK_HR(NodeList->get_length(&length));

for (long i = 0; i < length; i++)
{
if ( pNode ) pNode->Release();

CHK_HR( NodeList->get_item(i, &pNode) );

if(pNode )
{
if( CheckSubNodes( pNode ) == TRUE )
{
ReadSubNode( pNode, values );
}
else
{
ReadNodeValues( pNode, values );
}
}
}
}
}
else
{
// Failed to load xml, get last parsing error
CHK_HR(pXMLDom->get_parseError(&pXMLErr));
CHK_HR(pXMLErr->get_reason(&bstrErr));
printf("Failed to load DOM from %S. %S\n", varFileName, bstrErr);
}

CleanUp:
SAFE_RELEASE(pXMLDom);
SAFE_RELEASE(pXMLErr);
SAFE_RELEASE(NodeList);
SAFE_RELEASE(pNode);

SysFreeString(bstrXML);
SysFreeString(bstrErr);
SysFreeString(bstrQuery2);

VariantClear(&varFileName);
}

void CReadXML::ReadSubNode( IXMLDOMNode *pNode, std::list>& values )
{
HRESULT hr = S_OK;
HRESULT hResult;

IXMLDOMNode *pIAttrNode = NULL;
IXMLDOMNodeList *NodeList = NULL;
IXMLDOMNamedNodeMap *pDOMNamedNodeMap = NULL;
long length = 0;
std::pair pPair;

if( pNode )
{
CHK_HR( pNode->get_childNodes(&NodeList) );
if( NodeList )
{
CHK_HR( NodeList->get_length(&length) );

for( int i = 0; i < length; i++ )
{
if (pIAttrNode) pIAttrNode->Release();

CHK_HR( NodeList->get_item(i, &pIAttrNode));

if(pIAttrNode )
{
if( CheckSubNodes( pIAttrNode ) == TRUE )
{
ReadSubNode( pIAttrNode, values );
}
else
{
ReadNodeValues( pIAttrNode, values );
}
}
}
}
}

CleanUp:
SAFE_RELEASE(NodeList);
}

BOOL CReadXML::CheckSubNodes( IXMLDOMNode *pNode )
{
HRESULT hr = S_OK;
IXMLDOMNodeList *NodeList = NULL;
long length = 0;
VARIANT_BOOL varStatus = FALSE;

if( pNode )
{
CHK_HR( pNode->get_childNodes(&NodeList) );
if( NodeList )
{
CHK_HR( NodeList->get_length(&length) );

if( length > 0 )
varStatus = TRUE;
else
varStatus = FALSE;
}
}

CleanUp:
SAFE_RELEASE(NodeList);

return varStatus;
}

void CReadXML::ReadNodeValues( IXMLDOMNode *pNode, std::list>& values )
{
HRESULT hr = S_OK;

IXMLDOMNode* pParNode = NULL;

//Variables to store item's name, parent, text and node type:
BSTR bstrItemText, bstrItemNode, bstrNodeType;
std::pair pPair;

CHK_HR( pNode->get_nodeTypeString(&bstrNodeType));
//We process only elements (nodes of "Text" type):
BSTR temp = L"text";

if (lstrcmp((LPCTSTR)bstrNodeType, (LPCTSTR)temp)==0)
{
CHK_HR( pNode->get_parentNode( &pParNode ) );
if( pParNode )
{
CHK_HR( pParNode->get_nodeName(&bstrItemNode) );
//printf("Text: %ls\n", bstrItemNode);

CHK_HR( pNode->get_text(&bstrItemText) );
//printf("Text: %ls\n", bstrItemText);

pPair.first = ConvertBSTRToString(bstrItemNode);
pPair.second = ConvertBSTRToString(bstrItemText);
values.push_back( pPair);
}
}

CleanUp:
SAFE_RELEASE(pParNode);

}



For using this class create a C++ application and add the above files into that application.  After that create an object of the class "CReadXML" and call the function "LoadDOM".

eg:

        std::list> values;
CReadXML* pCReadXML = new CReadXML();
pCReadXML->LoadDOM("response_tunnel.xml", values);

After the function call you will get the values of XML file in the std::list values!.

Enjoy...!




Wednesday, February 13, 2013

Squiz Matrix

-->

Squiz Matrix

Install the following packages, for checking available packages, first you install "aptitude”, using the command “sudo apt-get install aptitude”, using “ / “ for find the packages, and use “ q” for quit from aptitude

Needed packages for Squiz Matrix
  1. vim
  2. apache2
  3. postgresql-9.1.7 or latest
  4. php5
  5. php5-cli
  6. php5-pgsql
  7. php-pear
  8. php5-curl
  9. php5-ldap
  10. php5-gd
  11. postfix
  12. cvs
  13. curl
  14. postfix
  15. PEAR

Use this command for install the above packages, if any one is existing, then ignore it from the list
Execute the following commands, as root or use sudo before the command...


apt-get update
apt-get install apache2 postgresql-9.1 php5 php5-cli php5-pgsql php-pear php5-curl php5-ldap php5-gd postfix cvs curl vim postfix

pear upgrade PEAR

pear install MDB2 Mail Mail_Mime XML_HTMLSax XML_Parser Text_Diff HTTP_Client Net_URL I18N_UnicodeNormalizer Mail_mimeDecode Mail_Queue HTTP_Request Image_Graph-0.8.0 Image_Color Image_Canvas-0.3.4 Numbers_Roman Numbers_Words-0.16.4 pear/MDB2#pgsql


Select “ local “ when you install postfix and enter the name


Settings for PostgreSQL

// Edit Postgres config
vim /etc/postgresql/9.1/main/pg_hba.conf
// Use trust for both
# Database administrative login by UNIX sockets
local all postgres trust
# "local" is for Unix domain socket connections only
local all all trust
// Restart Postgres
etc/init.d/postgresql restart
// Create users and DB
createuser -SRDU postgres matrix
createuser -SRDU postgres matrix_secondary
createdb -U postgres -O matrix -E UTF8 squiz_matrix
createlang -U postgres plpgsql squiz_matrix

Install Matrix

mkdir /home/websites
cd /home/websites
// Checkout and install Matrix
curl -O http://public-cvs.squiz.net/cgi-bin/viewvc.cgi/mysource_matrix/scripts/dev/checkout.sh?view=co
mv checkout.sh\?view\=co checkout.sh
sh checkout.sh mysource_4-12-3

Set Domain name

vim /etc/hosts
add the line

Init Matrix

// Init the main config
cd /home/websites/squiz_matrix
php install/step_01.php /home/websites/squiz_matrix
// Edit the main config file
vim data/private/conf/main.inc
// The following configuration settings need to be completed as a minimum

define('SQ_CONF_SYSTEM_ROOT_URLS', 'www.squizserver.com
');
define('SQ_CONF_DEFAULT_EMAIL', 'sabeesh.cs@sterian.com');
define('SQ_CONF_TECH_EMAIL', 'sabeesh.cs@sterian.com');
// Edit Database file
vim data/private/conf/db.inc
// Update the PHP array
$db_conf = array (
       'db' => array (
          'DSN' => 'pgsql:dbname=squiz_matrix',
          'user' => 'matrix',
          'password' => '',
          'type' => 'pgsql',
          ),
       'db2' => array (
          'DSN' => 'pgsql:dbname=squiz_matrix',
          'user' => 'matrix',
          'password' => '',
          'type' => 'pgsql',
          ),
       'db3' => array (
          'DSN' => 'pgsql:dbname=squiz_matrix',
          'user' => 'matrix_secondary',
          'password' => '',
          'type' => 'pgsql',
          ),
       'dbcache' => NULL,
       'dbsearch' => NULL,
       );

return $db_conf;

// Init database schema
php install/step_02.php /home/websites/squiz_matrix
// Install core asset types
php install/compile_locale.php /home/websites/squiz_matrix
php install/step_03.php /home/websites/squiz_matrix
php install/compile_locale.php /home/websites/squiz_matrix

Fix Permissions

Do this process as root user / use sudo before each command
chmod -R 755 /home/websites/squiz_matrix
cd /home/websites/squiz_matrix
chown -R www-data:www-data data cache
chmod -R g+w data cache

Apache

// Edit apache virtual hosts file
vim /etc/apache2/sites-enabled/000-default
//Remove existing, need to check this



ServerName server.example.com
DocumentRoot /home/websites/squiz_matrix/core/web

Options -Indexes FollowSymLinks


Order deny,allow
Deny from all


Order allow,deny
Allow from all


php_flag engine off



Order allow,deny
Deny from all


Order allow,deny
Deny from all


Alias /__fudge /home/websites/squiz_matrix/fudge
Alias /__data /home/websites/squiz_matrix/data/public
Alias /__lib /home/websites/squiz_matrix/core/lib
Alias / /home/websites/squiz_matrix/core/web/index.php/


// Restart apache
/etc/init.d/apache2 restart

Cron Setup

// Edit apache user cron file
crontab -u www-data -e
( select option 4 for editer )

// Add cron jobs
*/15 * * * * php /home/websites/squiz_matrix/core/cron/run.php
0 0 * * * /home/websites/squiz_matrix/scripts/session_cleanup.sh /home/websites/squiz_matrix
*/15 * * * * php /home/websites/squiz_matrix/packages/bulkmail/scripts/run.php

Install JRE 

 
 sudo apt-get purge openjdk*

After that, go and download Java JRE package from http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1880261.html . 
When prompted, save the download. Please select the 32 or 64 bit .tar.gz version file from the list.
After saving the file, go back to your terminal and run the below commands to extract the java packages you downloaded.
tar -xvf ~/Downloads/jre-7u13-linux-i586.tar.gz
Next, create your java 7 folder by running the commands below.
sudo mkdir -p /usr/lib/jvm/jre1.7.0
Then move all the extracted files and folders into the java 7 folder.
sudo mv jre1.7.0_13/* /usr/lib/jvm/jre1.7.0/
Next, run the commands below to install / update java 7
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jre1.7.0/bin/java 0
Next, create a plugin folder in your home directory by running the commands below.
mkdir ~/.mozilla/plugins 
Finally, link the java plugin to your profile.
ln -s /usr/lib/jvm/jre1.7.0/lib/i386/libnpjp2.so ~/.mozilla/plugins/

Load Firefox, Tools->Add-ons, select java, ( Quick java ) and install.

Load the “ www.squizserver.com “ and enjoy!

Tuesday, April 24, 2012



Prevent Expand\collapse event of treeview and load our functionality, if shift button is pressed.

Add Event "PreviewMouseDown" for the treeview,


pTreeView->PreviewMouseDown += gcnew System::Windows::Input::MouseButtonEventHandler(this, &OnPreviewMouseDown);



void OnPreviewMouseDown( System::Object^ sender, System::Windows::Input::MouseButtonEventArgs^ e)
{

if(System::Windows::Input::Keyboard::IsKeyDown(System::Windows::Input::Key::LeftShift) ||System::Windows::Input::Keyboard::IsKeyDown(System::Windows::Input::Key::RightShift))
{
System::Windows::Controls::TreeView^ pTreeView   = nullptr;
System::Windows::DependencyObject^ pDependencyObject = (System::Windows::DependencyObject^)e->OriginalSource;

pTreeView = (System::Windows::Controls::TreeView^)sender;
FindAncestor(pDependencyObject,System::Windows::Controls::TreeViewItem::typeid);
if(pDependencyObject)
{
System::Windows::Controls::TreeViewItem^ pTreeViewItem = (System::Windows::Controls::TreeViewItem^)pDependencyObject;
int iType = m_pCtrlAdmin->GetTreeitemType( (int)pTreeViewItem->Tag );
if( pTreeViewItem->Items->Count > 0 )
{
SetTreeviewAllItemState(iType);
e->Handled = true;
}

}

}
}



void FindAncestor(System::Windows::DependencyObject^% pDependencyObject,System::Type^ pType)
{
if(pDependencyObject->GetType() == pType)
return;
else
{
pDependencyObject = System::Windows::Media::VisualTreeHelper::GetParent(pDependencyObject);
if(pDependencyObject)
FindAncestor(pDependencyObject,pType);
else
return;
}
}


void SetTreeviewAllItemState(int iType)
{
    //Write your functionality

}


Thursday, October 27, 2011

Paper setting and read it in C++/CLI

Paper setting and read it in C++/CLI

[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = System::Runtime::InteropServices::CallingConvention::StdCall)]
static int DocumentProperties( System::IntPtr hwnd, System::IntPtr hPrinter, [MarshalAs(UnmanagedType::LPWStr)] System::String^ pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);

void OnBtnPropertiesClick( Object^ sender, RoutedEventArgs^ e )
{

System::Windows::Controls::ComboBoxItem^ pComboBoxItem = nullptr;
System::Printing::PrintQueue^ CurrentPrinter = nullptr;

pComboBoxItem = (System::Windows::Controls::ComboBoxItem^)m_CWPFDlgPrintPreview->m_CWPFDlgPrintPreview->CmbPrinter->SelectedItem;
if( pComboBoxItem->Tag != nullptr )
{
CurrentPrinter = (System::Printing::PrintQueue^)pComboBoxItem->Tag;
}

if( CurrentPrinter )
{
HWND pHWND = NULL;
System::IntPtr pHandle = System::IntPtr::Zero;
pHWND = m_CWPFDlgPrintPreview->GetHWND();

if( pHWND )
pHandle = (System::IntPtr)pHWND;

System::Printing::Interop::PrintTicketConverter^ PrintTicketConverter = nullptr;
PrintTicketConverter = gcnew System::Printing::Interop::PrintTicketConverter( CurrentPrinter->FullName, CurrentPrinter->ClientPrintSchemaVersion );
array ^myDevMode = PrintTicketConverter->ConvertPrintTicketToDevMode(CurrentPrinter->UserPrintTicket, System::Printing::Interop::BaseDevModeType::UserDefault);
System::Runtime::InteropServices::GCHandle^ pinnedDevMode = System::Runtime::InteropServices::GCHandle::Alloc(myDevMode, GCHandleType::Pinned);
System::IntPtr pDevMode = pinnedDevMode->AddrOfPinnedObject();
int result = DocumentProperties(pHandle, IntPtr::Zero, CurrentPrinter->FullName, pDevMode, pDevMode, 14);

if (result == 1)
{
CurrentPrinter->UserPrintTicket = PrintTicketConverter->ConvertDevModeToPrintTicket(myDevMode);
pinnedDevMode->Free();
// int PrintCopyCount = CurrentPrinter->UserPrintTicket->CopyCount->Value;
// SetPageOrientation(CurrentPrinter.UserPrintTicket.PageOrientation);
//SetCurrentPaper(CurrentPrinter->UserPrintTicket->PageMediaSize);
// ExecuteSetPrintingOptions(null);

m_CWPFDlgPrintPreview->PreparePrintContent();


}
}



void* WPFDialog::CWPFDlgPrintPreview::GetPrintQueue()
{

System::Runtime::InteropServices::GCHandle pGCHandle;
System::Windows::Controls::ComboBoxItem^ pComboBoxItem = nullptr;
System::Printing::PrintQueue^ l_pPrintQueue = nullptr;
System::Object^ pObject = nullptr;
void* pPrintQueueVoid;

if( m_CWPFDlgPrintPreview->CmbPrinter->SelectedIndex >= 0 )
{
pComboBoxItem = (System::Windows::Controls::ComboBoxItem^)m_CWPFDlgPrintPreview->CmbPrinter->SelectedItem;

if( pComboBoxItem->Tag != nullptr )
l_pPrintQueue = (System::Printing::PrintQueue^)pComboBoxItem->Tag;
}

if( l_pPrintQueue )
{
pObject = (System::Object^)l_pPrintQueue;

if( pObject )
{
pPrintQueueVoid = GCHandle::ToIntPtr(GCHandle::Alloc(pObject)).ToPointer();
}
}

return pPrintQueueVoid;


}


Load Print propertie from C++/CLI

Load Print propertie from C++/CLI

void OnProperties()
{
HANDLE hPrinter = NULL;
int sizeOfDevMode = 0;
DWORD dwRet = 0;
DEVMODE *pDevMode1 = NULL;
PRINTER_DEFAULTS pd;
BOOL bFlag;
LONG lFlag;

System::Drawing::Printing::PrinterSettings^ printerSettings = gcnew System::Drawing::Printing::PrinterSettings();
std::string pDevice = m_CWPFDlgPrintPreview->GetPrinterName();
System::String^ pPrinterName = gcnew System::String( pDevice.c_str() );

printerSettings->PrinterName = pPrinterName;

HWND pHWND = NULL;
System::IntPtr pHandle = System::IntPtr::Zero;
pHWND = m_CWPFDlgPrintPreview->GetHWND();

if( pHWND )
pHandle = (System::IntPtr)pHWND;

//pd.DesiredAccess = PRINTER_ALL_ACCESS;
pd.DesiredAccess = PRINTER_ACCESS_USE;
System::IntPtr thPrinter = (System::IntPtr)hPrinter;

if( !OpenPrinter(pPrinterName, thPrinter, pd) )
return;


IntPtr hDevMode = printerSettings->GetHdevmode();
IntPtr pDevMode = GlobalLock(hDevMode);
Int32 fMode = 0;
int sizeNeeded = DocumentPropertiesSize(pHandle, thPrinter, pPrinterName, pDevMode, pDevMode, fMode);
IntPtr devModeData = Marshal::AllocHGlobal(sizeNeeded);

//fMode = DM_OUT_BUFFER;

fMode = DM_IN_BUFFER | DM_PROMPT | DM_OUT_BUFFER;

DocumentProperties(pHandle, thPrinter, pDevice, devModeData, pDevMode, fMode);
GlobalUnlock(hDevMode);
printerSettings->SetHdevmode(devModeData);
printerSettings->DefaultPageSettings->SetHdevmode(devModeData);
GlobalFree(hDevMode);
Marshal::FreeHGlobal(devModeData);

}

Tuesday, August 16, 2011


For printing, in c++, we need to find the printer's aspect ratio. For get the printer/monitor's aspect ratio use this function


GetAspectRatio( HDC p_hDC, int& p_nAspectX, int& p_nAspectY )
{
//p_hDC is printer's /Monitor's handle

HDC l_hScreenDC = GetDC(NULL);
p_nAspectX = GetDeviceCaps( l_hScreenDC, LOGPIXELSX ) / GetDeviceCaps( p_hDC, LOGPIXELSX );
p_nAspectY = GetDeviceCaps( l_hScreenDC, LOGPIXELSY ) / GetDeviceCaps( p_hDC, LOGPIXELSY ) ;
}

Tuesday, June 14, 2011

RGB to long and Long to RGB

bool ReadColor(long nDecimal, int& nRVal,int& nGVal,int& nBVal)
{

/*nAVal = nDecimal & 0x000000FF;
nDecimal = nDecimal>>8;*/

nRVal = (nDecimal)& 0x000000FF;
nDecimal = nDecimal>>8;

nGVal = nDecimal & 0x000000FF;
nDecimal = nDecimal>>8;

nBVal = nDecimal & 0x000000FF;

return true;

}
bool CreateColor(long &nDecimal, int nRVal,int nGVal,int nBVal)
{


nDecimal = (nDecimal)& 0x00000000;
nDecimal = (nDecimal) | nBVal;
nDecimal = nDecimal<<8;
nDecimal = (nDecimal) | nGVal;
nDecimal = nDecimal<<8;
nDecimal = nDecimal | nRVal;
return true;



/*nDecimal = (nDecimal)& 0x00000000;
nDecimal = (nDecimal) | nRVal;
nDecimal = nDecimal<<8;
nDecimal = (nDecimal) | nGVal;
nDecimal = nDecimal<<8;
nDecimal = nDecimal | nBVal;
return true;*/
}

Wednesday, March 9, 2011

Store RGB values ( color values ) in a single variable and retrevie it back

bool ReadColor( long nDecimal, int& nRVal, int& nGVal, int& nBVal )
{

/*nAVal = nDecimal & 0x000000FF;
nDecimal = nDecimal>>8;*/

nRVal = (nDecimal)& 0x000000FF;
nDecimal = nDecimal>>8;

nGVal = nDecimal & 0x000000FF;
nDecimal = nDecimal>>8;

nBVal = nDecimal & 0x000000FF;

return true;

}

bool CreateColor(long &nDecimal, int nRVal, int nGVal, int nBVal )
{


nDecimal = (nDecimal)& 0x00000000;
nDecimal = (nDecimal) | nBVal;
nDecimal = nDecimal<<8;
nDecimal = (nDecimal) | nGVal;
nDecimal = nDecimal<<8;
nDecimal = nDecimal | nRVal;
return true;

}

Wednesday, October 6, 2010

Set DateFormat

We can set current application's date style using this in C++/CLI

System::Threading::Thread^ pThread;
System::Globalization::CultureInfo^ pCultureInfo;
pThread = System::Threading::Thread::CurrentThread;
pCultureInfo = (System::Globalization::CultureInfo^)pThread->CurrentCulture->Clone();
pCultureInfo->DateTimeFormat->ShortDatePattern = "dd.MM.yyyy";
pThread->CurrentCulture = pCultureInfo;

In WPF application, the same thing is doing
like

CultureInfo culutreInfo = System.Threading.Thread.CurrentThread.CurrentCulture.Clone() as CultureInfo;
culutreInfo.DateTimeFormat.ShortDatePattern = "MMM dd/yyyy";
System.Threading.Thread.CurrentThread.CurrentCulture = culutreInfo;

or

Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";

Also we can set a particular datepicker's date format like this,

CultureInfo cultureInfo = new CultureInfo("en-US");
DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();
dateInfo.ShortDatePattern = "MM/yyyy";
cultureInfo.DateTimeFormat = dateInfo;
radDatePicker1.Culture = cultureInfo;


or

CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "MMM/dd/yyyy";
datePicker1.Culture = culture;

Sunday, September 19, 2010

Call a new function from button click with arguments in C++/CLI

//FirstWindow.h
#pragma once

using namespace System; using namespace System::Windows; using namespace System::Windows::Controls;

ref class Functor;

ref class FirstWindow : Window { Canvas^ maincanvas; Button^ addbutton1; Button^ addbutton2; Functor^ pFunctor; public: FirstWindow(void); void InitControls(void); void MyFunction( int x, int y );

};

//FirstWindow.cpp #include "FirstWindow.h" #include "Functor.h"

FirstWindow::FirstWindow(void) { Title = "First Avalon App"; Width = 400; Height = 400; ResizeMode = System::Windows::ResizeMode::NoResize;

InitControls();

}

void FirstWindow::InitControls(void) { addbutton1 = gcnew Button(); addbutton1->Width = 80; addbutton1->Height = 25; addbutton1->Content = "Add"; pFunctor = gcnew Functor(this, 10, 20); addbutton1->Click += gcnew RoutedEventHandler( pFunctor, &Functor::Handler);

    Canvas::SetTop(addbutton1, 45);
Canvas::SetLeft(addbutton1, 200);


pFunctor
= gcnew Functor(this, 100, 200);
addbutton2
= gcnew Button();
addbutton2
->Width = 80;
addbutton2
->Height = 25;
addbutton2
->Content = "Add";
addbutton2
->Click += gcnew RoutedEventHandler(pFunctor, &Functor::Handler);

Canvas::SetTop(addbutton2, 85);
Canvas::SetLeft(addbutton2, 200);


maincanvas
= gcnew Canvas();

maincanvas
->Children->Add(addbutton1);
maincanvas
->Children->Add(addbutton2);
Content = maincanvas;

}

void FirstWindow::MyFunction( int x, int y ) { MessageBox::Show("This function is call by Button Click with values " + x.ToString() + " , " + y.ToString() ); }

//Functor.h #pragma once

using namespace System; using namespace System::Windows; using namespace System::Windows::Controls;

ref class FirstWindow;

private ref class Functor { public: Functor(FirstWindow^ pFirstWindow, int pFirstArg, int pSecArg);

// This is what we will use as the handler method
void Handler(Object ^ sender, RoutedEventArgs ^ e);

private: int m_pFirstArg; int m_pSecArg; FirstWindow^ m_pFirstWindow; };

//Functor.cpp

#include "Functor.h" #include "FirstWindow.h"

Functor::Functor(FirstWindow^ pFirstWindow, int pFirstArg, int pSecArg) : m_pFirstWindow( pFirstWindow ), m_pFirstArg(pFirstArg), m_pSecArg( pSecArg ) {

}

void Functor::Handler(Object ^ sender, RoutedEventArgs ^ e) { if ( m_pFirstWindow ) m_pFirstWindow->MyFunction(m_pFirstArg, m_pSecArg );

}

Now when we click on button one, then the application call the function "MyFunction" with value 10,20 and when we click on button 2 then the same function "MyFunction" with value 100,200.

Saturday, September 11, 2010

Load Controls from WPF window using C++/CLI

void FindChildren(System::Windows::DependencyObject^ source, List^ pList)
{
System::Collections::Generic::List^ pDependencyObject = nullptr;
pDependencyObject = gcnew System::Collections::Generic::List();

if (source != nullptr)
{
GetChildObjects(source, pDependencyObject);

for each ( System::Windows::DependencyObject^ child in pDependencyObject)
{
if ( dynamic_cast(child) )
{
//MessageBox::Show ( "Yes Add" + child->GetType()->ToString());
pList->Add( (System::Windows::Controls::Control^)child );
}
//else
//MessageBox::Show ( "Not need" + child->GetType()->ToString());

}
}

}

void GetChildObjects(System::Windows::DependencyObject^ parent, System::Collections::Generic::List^ pDependencyObject)
{
bool bContentElement = false;
bool bFrameworkElement = false;

if (parent == nullptr)
return;

if ( dynamic_cast(parent) )
bContentElement = true;
else
bContentElement = false;


if ( dynamic_cast(parent) )
bFrameworkElement = true;
else
bFrameworkElement = false;

if ( ( bContentElement == true ) || ( bFrameworkElement == true ) )
{
for each (System::Object^ obj in System::Windows::LogicalTreeHelper::GetChildren(parent))
{
System::Windows::DependencyObject^ depObj = nullptr;
if ( dynamic_cast(obj) )
depObj = (System::Windows::DependencyObject^)obj;

if (depObj != nullptr)
{
pDependencyObject->Add( (System::Windows::DependencyObject^)obj );
//MessageBox::Show( ((System::Windows::DependencyObject^)obj)->GetType()->ToString() );
GetChildObjects( (System::Windows::DependencyObject^)obj, pDependencyObject );
}
}
}
}


call the function

List^ pControlList = nullptr;
pControlList = gcnew List();

FindChildren(pDialog, pControlList); //Load controls from dialog

for each ( System::Windows::Controls::Control^ pControl in pControlList )
{
//your checking
}
My Blog - Windows Live: "- Sent using Google Toolbar"

Monday, April 19, 2010

Wake On LAN

General

How can I start a computer over the network?

There are two different procedures, depending on whether the target computer is in standby/sleep/suspend mode or whether it is actually powered down in hibernate mode or entirely off.

Note that you cannot wake a computer that is powered down over a WLAN connection. Only cable connections will do.

Waking from suspend mode

  1. On the target computer in Device Manager or in the network settings select the network card.
  2. Click on: Properties
  3. Click on the configure button of the network card.
  4. Select the tab: Power management
  5. Set a check mark at: Allow this device to bring the computer out of standby
  6. Click on: OK
  7. Continue to close all property pages.

Now your computer should wake up from standby whenever the network card is accessed by any other computer. If it doesn't, check any relevant BIOS settings, but usually there aren't any.

A frequent problem is that the computer is woken up by all and sundry network traffic, hence it may be better to send the computer to hibernate mode or shut it down and off altogether and use the following method.

Wake On LAN from hibernate or off mode

One way to do this is the following.

  1. Check whether the network adapter on the target computer supports Wake On LAN. Enable the function in the network adapter settings or in any special management program that came with it. If the network adapter is integrated on the motherboard, enable Wake On LAN in the motherboard BIOS.
  2. Download and install WakeOnLanGui from www.depicus.com.
  3. On the target computer, i.e. the one to be woken up, open a command line window and enter the command: ipconfig /all
  4. Note the physical address (sometimes called MAC = Media Access Control address) of your Ethernet adapter from the ipconfig output. Example: 00-E0-18-90-A5-44
  5. Run WakeOnLanGui on the computer from which you want to wake the other computer and type the physical address into the proper field in WakeOnLanGui. The other two fields are filled with 255.255.255.255, and the port is 7 or actually any other port. Port 9 is sometimes used.
  6. Shut down the computer to be waked.
  7. Test WakeOnLanGui.

If you need the opposite function as well, to shut down a computer remotely, have a look at:

http://www.microsoft.com/technet/sysinternals/utilities/PsShutdown.mspx

This program, PsShutdown, is a member of Sysinternals' PsTools group of freeware utilities.

To shut down and power down a remote computer named "computername", enter the command:

psshutdown -k -f -t 00 \\computername

-k indicates shutdown and powerdown, -f means force all running programs to close without asking, and -t 00 means don't wait (wait zero seconds) until shutting down the computer named computername. (Don't miss the required space between -t and 00.) This utility can do several other things as well, like sending the target computer into hibernate mode or rebooting it.

Wake On LAN over the Internet

One example of how to wake up a home or office computer across the Internet is the following.

Assume a home network with a WAN router, in this case a DrayTek Vigor 2500We with firmware version 2.54. The main problem is that you cannot use any of the usual methods to address the target computer. Since it is off, it has no IP address. False advice is widespread, because people keep forgetting this simple fact.

The router has to send a special broadcast packet into the Local Area Network, using the MAC (Media Access Control) address, rather than the IP address. With some routers you may be able to achieve this by sending a Wake-On-LAN packet to the router and forward the port to an internal broadcast address, for example: 192.168.0.255

With most routers, however, this still does not work. You have to rely on the router to have the special ability to forward or send a Wake-On-LAN broadcast packet. In the case of the DrayTek router this can only be achieved through the telnet interface, but unfortunately not yet through the Web interface. An example for the telnet command for this DrayTek router is:

wol up 00E01890A545

Of course you have to replace the hex number with the MAC address of your target computer, and for this particular router you cannot intersperse hyphens as usual. The router needs the address in the direct short hexadecimal format. Check your router's manual or help system for its specifics.


Wake On Lan Command Line

Wake on Lan Command Line

http://www.depicus.com/wake-on-lan/wake-on-lan-cmd.aspx

The command line tool wolcmd is run from a dos prompt. The syntax is as follows:

wolcmd [mac address] [ip address] [subnet mask] [port number]

you can also do a local broadcast if you are running on an internal network thus

wolcmd [macaddress] 255.255.255.255 255.255.255.255

where mac address is the unique address of the network card. To find the mac address of a card you can either open the computer and read the address on the sticker on the card or much easier is, if you are using TCP/IP, ping the machine from a dos prompt (ping [machine name or ip number] i.e. ping delphi or ping 10.43.43.43) then issue an arp command (arp -a) which will list the ip number and physical address of the card.

If the port number is not specified it will default to port 7

Running from a batch file

Simply add multiple entries thus:

wolcmd 009027a324fe 195.188.159.20 255.255.255.0 8900
wolcmd 009024a731da 212.86.64.31 255.255.255.0 8900

To run the batch file, say half an hour before everybody gets into work, use the AT command on a Windows NT computer.

The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. The syntax is as follows:

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
[ /EVERY:date[,...] | /NEXT:date[,...]] "command"


\\computername Specifies a remote computer. Commands are scheduled on local computer if this parameter is omitted.
id Is an identification number assigned to a scheduled command.
/delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are cancelled.
/yes Used with cancel all jobs command when no further confirmation is desired.
time Specifies the time when command is to run.
/interactive Allows the job to interact with the desktop of the use who is logged on at the time the job runs.
/every:date[,...] Runs the command on each specified day(s) of the week month. If date is omitted, the current day of the month is assumed.
/next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, current day of the month is assumed.
"command" Is the Windows NT command, or batch program to be run.


Example

wolcmd 00:1D:7D:22:DC:F0 192.168.1.86 255.255.255.128

wolcmd 001D7D22DCF0 192.168.1.86 255.255.255.128


Tuesday, January 12, 2010

Keyboard Listener in WPF

Key board message Hooking in WPF, using C++/CLI

KeyboardListener.h
==================
#pragma once

using namespace System;
using namespace System::Diagnostics;
using namespace System::Runtime::InteropServices;
using namespace System::Runtime::CompilerServices;
using namespace System::Windows::Input;
using namespace System::Windows::Interop;

public ref class CKeyboardListener : System::IDisposable
{

public:
CKeyboardListener(void);
~CKeyboardListener(void);

public:
delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
static LowLevelKeyboardProc^ m_pLowLevelKeyboardProc;

public:
void DisposeHook(void);
static IntPtr SetHook( LowLevelKeyboardProc^ pLowLevelKeyboardProc );
static IntPtr GetWindowHandle(System::Windows::Window^ window );
static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam);

private:
static const int WH_KEYBOARD_LL = 13;
static const int WM_KEYDOWN = 0x0100;
static System::IntPtr m_hookID = IntPtr::Zero;

public :
[DllImport("user32.dll", CharSet = CharSet::Auto, SetLastError = true)]
static IntPtr SetWindowsHookEx(int idHook,LowLevelKeyboardProc^ lpfn, System::IntPtr hMod, unsigned int dwThreadId);

[DllImport("user32.dll", CharSet = CharSet::Auto, SetLastError = true)]
//[return: MarshalAs(UnmanagedType::Bool)]
static bool UnhookWindowsHookEx(System::IntPtr hhk);

[DllImport("user32.dll", CharSet = CharSet::Auto, SetLastError = true)]
static System::IntPtr CallNextHookEx(System::IntPtr hhk, int nCode,
System::IntPtr wParam, System::IntPtr lParam);

[DllImport("kernel32.dll", CharSet = CharSet::Auto, SetLastError = true)]
static IntPtr GetModuleHandle(System::String^ lpModuleName);

[ DllImport("user32.dll") ]
static IntPtr GetForegroundWindow();
};

KeyboardListener.cpp
================
#include "KeyboardListener.h"
#include "MainApp.h"

CKeyboardListener::CKeyboardListener(void)
{
m_pLowLevelKeyboardProc = gcnew LowLevelKeyboardProc( &CKeyboardListener::HookCallback);
m_hookID = SetHook( m_pLowLevelKeyboardProc );
}

CKeyboardListener::~CKeyboardListener(void)
{

}

void CKeyboardListener::DisposeHook(void)
{
UnhookWindowsHookEx( m_hookID );
}

IntPtr CKeyboardListener::SetHook(LowLevelKeyboardProc^ pLowLevelKeyboardProc)
{
Process^ curProcess = nullptr;
ProcessModule^ curModule = nullptr;

while( curProcess = Process::GetCurrentProcess() )
{
while( curModule = curProcess->MainModule )
{
return SetWindowsHookEx(WH_KEYBOARD_LL, pLowLevelKeyboardProc,
GetModuleHandle(curModule->ModuleName), 0);
}
}

return System::IntPtr::Zero;
}

IntPtr CKeyboardListener::GetWindowHandle(System::Windows::Window^ window )
{
System::Windows::Interop::WindowInteropHelper^ pWindow;
pWindow = gcnew System::Windows::Interop::WindowInteropHelper(window);
return pWindow->Handle;
}

IntPtr CKeyboardListener::HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
int l_nWindowCnt = 0;
System::IntPtr l_hForeGndWnd = GetForegroundWindow();
MainApp^ l_pCurApp = (MainApp^) Application::Current;
int l_nVirtualKeyCode = 0;

l_nVirtualKeyCode = Marshal::ReadInt32(lParam);

if ( l_nVirtualKeyCode == 112 ) //If F1 key
{
for each (Window^ hWindow in l_pCurApp->Windows)
{
++l_nWindowCnt;

System::IntPtr l_hWindow = GetWindowHandle(hWindow);

if ( l_hForeGndWnd == l_hWindow )
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
((MainScreen^)l_pCurApp->mainwnd)->LoadHelp(); //Call the LoadHelp function from MainScreen class
return CallNextHookEx( m_hookID, nCode, wParam, lParam);
}
}
}
}

return System::IntPtr::Zero;
}


And in MainApp.cpp we create an instance of the class "CKeyboardListener"

void MainApp::OnStartup( System::Windows::StartupEventArgs^ e )
{
Application::OnStartup(e);
mainwnd = gcnew MainScreen(ResourceAssembly->Location);
m_pKeyboardListener = gcnew CKeyboardListener(); //Start the key board hooking

mainwnd->Show();
}

void MainApp::OnExit( System::Windows::ExitEventArgs^ e )
{
m_pKeyboardListener->DisposeHook();
m_pKeyboardListener = nullptr;
}



Friday, December 11, 2009

Custom Command Button in WPF

Hi,
Here I create custom WPF command button using C++/CLI.

//.h file
#pragma once

using namespace System;
using namespace System::Windows;
using namespace System::Windows::Controls;

ref class MyButton: public System::Windows::Controls::Button
{
public:
MavisButton();
~MavisButton();
void SetControl();
};

//.cpp file

#include "MyButton.h"

MyButton::MyButton()
{
this->SetControl();
}

MyButton::~MyButton()
{

}

void MyButton::SetControl()
{
System::Windows::Controls::ControlTemplate^ pControlTemplate;

System::Drawing::ColorConverter^ pColorConverter;
System::Windows::Media::RadialGradientBrush^ pGradient_HoverGlassBackgroundFill;
System::Windows::Media::LinearGradientBrush^ pHighlightFill;
System::Windows::Media::LinearGradientBrush^ pBorderStroke;

System::Windows::Setter^ pSetter;
System::Windows::Style^ pStyle;

System::Windows::Trigger^ tg_IsMouseOver;
System::Windows::Trigger^ tg_IsPressed;

System::Windows::Setter^ str_IsPressed;
System::Windows::Setter^ str_IsMouseOver;


//-----------------------------------------------GlassBackgroundFill-------------------------------------------------------------

pColorConverter = gcnew System::Drawing::ColorConverter();
System::Windows::Media::LinearGradientBrush^ gradient_GlassBackgroundFill = gcnew System::Windows::Media::LinearGradientBrush();
gradient_GlassBackgroundFill->StartPoint = System::Windows::Point(0, 0);
gradient_GlassBackgroundFill->EndPoint = System::Windows::Point(0, 1);
gradient_GlassBackgroundFill->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#FF4B58" )), 0) );
gradient_GlassBackgroundFill->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#A91E28" )), 1) );

//--------------------------------------------------HoverGlassBackgroundFill-------------------------------------------------------------

pGradient_HoverGlassBackgroundFill = gcnew System::Windows::Media::RadialGradientBrush();
pGradient_HoverGlassBackgroundFill->Center = System::Windows::Point(0.5, 0.5);

pGradient_HoverGlassBackgroundFill->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#a91e28" )), 0 ));
pGradient_HoverGlassBackgroundFill->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#ff4b58" )), 1 ));

//-------------------------------------------HighlightFill------------------------------------------------------------

pHighlightFill = gcnew System::Windows::Media::LinearGradientBrush();
pHighlightFill->StartPoint = System::Windows::Point(0, 0);
pHighlightFill->EndPoint = System::Windows::Point(0, 1);

pHighlightFill->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#FFFFFFFF" )), 0 ));
pHighlightFill->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#00000000" )), 1 ));

//-----------------------------------------------------BorderStroke-------------------------------------------------------
pBorderStroke = gcnew System::Windows::Media::LinearGradientBrush();
pBorderStroke->StartPoint = System::Windows::Point(0, 0);
pBorderStroke->EndPoint = System::Windows::Point(0, 1);

pBorderStroke->GradientStops->Add( gcnew System::Windows::Media::GradientStop(( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#c7c7c7" )), 0 ));
pBorderStroke->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#b0b0b0" )), 1 ));

//--------------------------------------------------------------------------------------------------

pControlTemplate = gcnew System::Windows::Controls::ControlTemplate();
pControlTemplate->TargetType = (gcnew System::Windows::Controls::Button)->GetType();

System::Windows::FrameworkElementFactory^ pFrameworkElementFactoryGrid = gcnew System::Windows::FrameworkElementFactory( (gcnew System::Windows::Controls::Grid)->GetType() );
pFrameworkElementFactoryGrid->Name ="Grid";
pFrameworkElementFactoryGrid->SetValue( System::Windows::Controls::Grid::RenderTransformOriginProperty, System::Windows::Point(0.5, 0.5));

//--------------------------------------------------------------------------------------------------------------

System::Windows::FrameworkElementFactory^ pFrameworkElementFactoryBorder = gcnew System::Windows::FrameworkElementFactory( (gcnew System::Windows::Controls::Border)->GetType() );
pFrameworkElementFactoryBorder->Name = "Outline";
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::CornerRadiusProperty, gcnew System::Windows::CornerRadius(12.0));
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::BackgroundProperty, System::Windows::Media::Brushes::Red);
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::BorderBrushProperty, pBorderStroke ) ;
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::BorderThicknessProperty, gcnew System::Windows::Thickness(1));

System::Windows::FrameworkElementFactory^ pFrameworkElementFactoryBackground = gcnew System::Windows::FrameworkElementFactory( (gcnew System::Windows::Shapes::Rectangle)->GetType() );
pFrameworkElementFactoryBackground->Name = "GlassBackground";
pFrameworkElementFactoryBackground->SetValue( System::Windows::Shapes::Rectangle::MarginProperty , System::Windows::Thickness(1, 1, 2, 2));
pFrameworkElementFactoryBackground->SetValue( System::Windows::Shapes::Rectangle::RadiusXProperty, 9.0 );
pFrameworkElementFactoryBackground->SetValue( System::Windows::Shapes::Rectangle::RadiusYProperty, 9.0 ) ;
pFrameworkElementFactoryBackground->SetValue( System::Windows::Shapes::Rectangle::FillProperty, gradient_GlassBackgroundFill );

System::Windows::FrameworkElementFactory^ pFrameworkElementFactoryHighlight = gcnew System::Windows::FrameworkElementFactory( (gcnew System::Windows::Shapes::Rectangle)->GetType() );
pFrameworkElementFactoryHighlight->Name = "Highlight";
pFrameworkElementFactoryHighlight->SetValue( System::Windows::Shapes::Rectangle::MarginProperty , System::Windows::Thickness(1, 1, 2, 2));
pFrameworkElementFactoryHighlight->SetValue( System::Windows::Shapes::Rectangle::RadiusXProperty, 9.0 );
pFrameworkElementFactoryHighlight->SetValue( System::Windows::Shapes::Rectangle::RadiusYProperty, 9.0 ) ;
pFrameworkElementFactoryHighlight->SetValue( System::Windows::Shapes::Rectangle::OpacityProperty, 1.0 ) ;
pFrameworkElementFactoryHighlight->SetValue( System::Windows::Shapes::Rectangle::FillProperty, pHighlightFill );

System::Windows::FrameworkElementFactory^ pFrameworkElementFactoryContentPresenter = gcnew System::Windows::FrameworkElementFactory( (gcnew System::Windows::Controls::ContentPresenter)->GetType() );
pFrameworkElementFactoryContentPresenter->SetValue ( System::Windows::Controls::ContentPresenter::VerticalAlignmentProperty, System::Windows::VerticalAlignment::Center );
pFrameworkElementFactoryContentPresenter->SetValue ( System::Windows::Controls::ContentPresenter::HorizontalAlignmentProperty, System::Windows::HorizontalAlignment::Center );

pFrameworkElementFactoryGrid->AppendChild( pFrameworkElementFactoryBorder );
pFrameworkElementFactoryGrid->AppendChild( pFrameworkElementFactoryBackground );
pFrameworkElementFactoryGrid->AppendChild( pFrameworkElementFactoryHighlight );
pFrameworkElementFactoryGrid->AppendChild( pFrameworkElementFactoryContentPresenter );

pControlTemplate->VisualTree = pFrameworkElementFactoryGrid;


//------------------------------------------------ControlTemplate->Triggers->IsMouseOver---------------------------------------------------------

tg_IsMouseOver = gcnew System::Windows::Trigger();
tg_IsMouseOver->Property = System::Windows::UIElement::IsMouseOverProperty;
tg_IsMouseOver->Value = true;

str_IsMouseOver = gcnew System::Windows::Setter();
str_IsMouseOver->TargetName = "GlassBackground";
str_IsMouseOver->Property = System::Windows::Shapes::Rectangle::FillProperty;
str_IsMouseOver->Value = pGradient_HoverGlassBackgroundFill;
tg_IsMouseOver->Setters->Add( str_IsMouseOver );

pControlTemplate->Triggers->Add ( tg_IsMouseOver );

//------------------------------------------------ControlTemplate.Triggers.IsPressed---------------------------------------------------------

tg_IsPressed = gcnew System::Windows::Trigger();
tg_IsPressed->Property = System::Windows::Controls::Button::IsPressedProperty;
tg_IsPressed->Value = true;

str_IsPressed = gcnew System::Windows::Setter();
str_IsPressed->TargetName = "GlassBackground";
str_IsPressed->Property = System::Windows::Shapes::Rectangle::FillProperty;
str_IsPressed->Value = System::Windows::Media::Brushes::Red;
tg_IsPressed->Setters->Add( str_IsPressed );

pControlTemplate->Triggers->Add ( tg_IsPressed );

this->Template = pControlTemplate;

//Style
pStyle = gcnew System::Windows::Style();
pStyle->TargetType = (gcnew System::Windows::Controls::Button)->GetType();

//Margin
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Button::MarginProperty, gcnew System::Windows::Thickness(1.0));
pStyle->Setters->Add( pSetter );

//SnapsToDevicePixelsProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Button::SnapsToDevicePixelsProperty, true);
pStyle->Setters->Add( pSetter );

//OverridesDefaultStyleProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Button::OverridesDefaultStyleProperty, true);
pStyle->Setters->Add( pSetter );

//MinHeightProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Button::MinHeightProperty, 16.0 );
pStyle->Setters->Add( pSetter );

//MinWidthProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Button::MinWidthProperty, 16.0 );
pStyle->Setters->Add( pSetter );

//FontFamilyProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Button::FontFamilyProperty, gcnew System::Windows::Media::FontFamily("Verdana") );
pStyle->Setters->Add( pSetter );

//FontSizeProperty
System::Windows::FontSizeConverter^ pFontSizeConverter = gcnew System::Windows::FontSizeConverter();
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Button::FontSizeProperty, (double)pFontSizeConverter->ConvertFromString("11px"));
pStyle->Setters->Add( pSetter );

//ForegroundProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Button::ForegroundProperty, System::Windows::Media::Brushes::White);
pStyle->Setters->Add( pSetter );

//TemplateProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Control::TemplateProperty, pControlTemplate );
pStyle->Setters->Add( pSetter );

this->Style = pStyle;

}



How to use this contorl in your application

MavisButton^ m_pOkButton = gcnew MavisButton();
m_pOkButton->Width = 80;
m_pOkButton->Height = 25;
m_pOkButton->Content = "OK";
m_pOkButton->Click += gcnew System::Windows::RoutedEventHandler( this, &AboutScreen::OKButton_Click );
Canvas::SetTop( m_pOkButton, 360 );
Canvas::SetLeft( m_pOkButton, 260 );

m_MainCanvas->Children->Add ( m_pOkButton );

Custom ToolTip in WPF

Hi,

I create a static class for set a tooltip style in VC++, using WPF and C++/CLI. Using this class we can set the custom tooltip style for our WPF application.

Eg:

System::Windows::Controls::ToolTip^ pToolTip = gcnew System::Windows::Controls::ToolTip();

pToolTip->Style = mvdata::CToolTipStyle::ToopTipStyle( "Tool tip Text" );
System::Windows::Controls::YourControl->ToolTip = pToolTip;
//pSubMenuItem->ToolTip = pToolTip;


#pragma once
#include "stdafx.h"

//Class for SetToolTip Style

namespace myTooltipStyle
{
public ref class CToolTipStyle
{
private:
static CToolTipStyle()
{

}

public:
static System::Windows::Style^ ToopTipStyle(System::String^ pToolTipText)
{
System::Windows::Style^ pToopTipStyle;
System::Windows::Setter^ pSetter;

System::Windows::Controls::ControlTemplate^ pControlTemplate;
System::Windows::Media::LinearGradientBrush^ pBorderStroke;
System::Windows::Media::LinearGradientBrush^ pBackground;

//-----------------------------------------------------Background-------------------------------------------------------
pBackground = gcnew System::Windows::Media::LinearGradientBrush();
pBackground->StartPoint = System::Windows::Point(0.5, 0);
pBackground->EndPoint = System::Windows::Point(0.5, 1);

pBackground->GradientStops->Add( gcnew System::Windows::Media::GradientStop(( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#CF181818" )), 0 ));
pBackground->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#BE1C1C1C" )), 1 ));

//-----------------------------------------------------BorderStroke-------------------------------------------------------
pBorderStroke = gcnew System::Windows::Media::LinearGradientBrush();
pBorderStroke->StartPoint = System::Windows::Point(0.5, 0);
pBorderStroke->EndPoint = System::Windows::Point(0.5, 1);

pBorderStroke->GradientStops->Add( gcnew System::Windows::Media::GradientStop(( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#80FFFFFF" )), 0 ));
pBorderStroke->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#7FFFFFFF" )), 1 ));
pBorderStroke->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#FFFFF18D" )), 0.344 ));
pBorderStroke->GradientStops->Add( gcnew System::Windows::Media::GradientStop( ( System::Windows::Media::Color)( System::ComponentModel::TypeDescriptor::GetConverter( System::Windows::Media::Color::typeid )->ConvertFromString( "#FFFFF4AB" )), 0.647 ));

//--------------------------------------------------------------------------------------------------

pControlTemplate = gcnew System::Windows::Controls::ControlTemplate();
pControlTemplate->TargetType = (gcnew System::Windows::Controls::ToolTip)->GetType();

System::Windows::FrameworkElementFactory^ pFrameworkElementFactoryBorder = gcnew System::Windows::FrameworkElementFactory( (gcnew System::Windows::Controls::Border)->GetType() );
pFrameworkElementFactoryBorder->Name = "Outline";
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::CornerRadiusProperty, gcnew System::Windows::CornerRadius(7.0));
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::HorizontalAlignmentProperty, System::Windows::HorizontalAlignment::Center);
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::VerticalAlignmentProperty, System::Windows::VerticalAlignment::Top);
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::PaddingProperty, System::Windows::Thickness(5));
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::BorderThicknessProperty, gcnew System::Windows::Thickness(3));
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::BackgroundProperty, pBackground );
pFrameworkElementFactoryBorder->SetValue( System::Windows::Controls::Border::BorderBrushProperty, pBorderStroke ) ;

System::Windows::FrameworkElementFactory^ pFrameworkElementFactoryStackPanal = gcnew System::Windows::FrameworkElementFactory( (gcnew System::Windows::Controls::StackPanel)->GetType() );
pFrameworkElementFactoryStackPanal->Name = "StackPanal";


System::Windows::FrameworkElementFactory^ pFrameworkElementFactoryTextBlock = gcnew System::Windows::FrameworkElementFactory( (gcnew System::Windows::Controls::TextBlock)->GetType() );
pFrameworkElementFactoryStackPanal->Name = "TextBlock";
pFrameworkElementFactoryTextBlock->SetValue( System::Windows::Controls::TextBlock::ForegroundProperty, System::Windows::Media::Brushes::White);
pFrameworkElementFactoryTextBlock->SetValue( System::Windows::Controls::TextBlock::TextProperty, pToolTipText );

pFrameworkElementFactoryStackPanal->AppendChild( pFrameworkElementFactoryTextBlock );
pFrameworkElementFactoryBorder->AppendChild( pFrameworkElementFactoryStackPanal );

pControlTemplate->VisualTree = pFrameworkElementFactoryBorder;


pToopTipStyle = gcnew System::Windows::Style();
pToopTipStyle->TargetType = (gcnew System::Windows::Controls::ToolTip)->GetType();


//OverridesDefaultStyleProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::ToolTip::OverridesDefaultStyleProperty, true);
pToopTipStyle->Setters->Add( pSetter );


//HasDropShadowProperty
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::ToolTip::HasDropShadowProperty, true);
pToopTipStyle->Setters->Add( pSetter );

//Template
pSetter = gcnew System::Windows::Setter( System::Windows::Controls::Control::TemplateProperty, pControlTemplate );
pToopTipStyle->Setters->Add( pSetter );


return pToopTipStyle;

}
};

}