Code Repo    |     RSS
MD's Technical Sharing



Saturday, February 28, 2009

VB.NET With statement

The following code will run flawlessly but at the end, Obj will still contain the assigned properties (.prop1 = 0 and .prop2 = "hello") and is not a new instance of ObjType. The attempt to assign a new instance of ObjType to obj has no effect as the reference to obj will be reverted to the original value when the code gets out of the With block.


With Obj
.prop1 = 0
.prop2 = "hello"

obj =
new ObjType()
End With

Read More »

Sunday, February 22, 2009

How to get path of the current system's temporary folder using .NET

Temporary folders are useful to store simple logs during execution of the program. It is also used for storing the decompressed files before any operation. The folder location varies from OS to OS. The following C# snippet would help in retrieving the Temporary folder path

string sPath;
sPath
= Path.GetTempPath();
Console
.WriteLine("Temporary Path := " + sPath );

Read More »

Saturday, February 21, 2009

Bit-fields in C++

Classes and structures can contain members that occupy less storage than an integral type. These members are specified as bit fields. The syntax for bit-field member-declarator specification follows:

declaratoropt : constant-expression


The declarator is the name by which the member is accessed in the program. It must be an integral type (including enumerated types). The constant-expression specifies the number of bits the member occupies in the structure. Anonymous bit fields — that is, bit-field members with no identifier — can be used for padding.


Note An unnamed bit field of width 0 forces alignment of the next bit field to the next type boundary, where type is the type of the member.


The following example declares a structure that contains bit fields


struct Date
{
unsigned nWeekDay : 3; // 0..7 (3 bits)
unsigned nMonthDay : 6; // 0..31 (6 bits)
unsigned nMonth : 5; // 0..12 (5 bits)
unsigned nYear : 8; // 0..100 (8 bits)
};

int main()
{
}

Read More »

Accessing WIN32 API functions from C++ CLI

First, add the following declaration to stdafx.h:

// TODO: reference additional headers your program requires here
#include "windows.h"

For example, when calling SendMessage, take note of the double colon at the beginning:
::SendMessage((HWND)this->button1->Handle.ToInt32(), WM_LBUTTONDOWN, 0, 0);

The following would not work:
SendMessage((HWND)this->button1->Handle.ToInt32(), WM_LBUTTONDOWN, 0, 0);

and result in the following error:
error C2661: 'System::Windows::Forms::Control::SendMessage' : no overloaded function takes 4 arguments

If the error still persists, check Project Properties->Linker->Input->Additional dependencies. Click the button with the dots and turn on the checkbox for "Inherit from parent…"
Read More »

Wednesday, February 18, 2009

How to disable WebBrowser control's ‘click sound’

Depending on system preferences (in Control Panel/Sounds), the .NET WebBrowser control (just like Internet Explorer) may produce a click sound when certain events are done to it (e.g. back/forward navigation, DocumentText changes, etc.)

To avoid this:

Method 1: Do not changes the web browser document text via the DocumentText property. So instead of this:

webBrowser1.DocumentText = "<h1>Hello, world!</h1>";

try this:


webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("<h1>Hello, world!</h1>");


Side-effects: This cause the web browser to steal focus from the active application when OpenNew is called!

Method 2: Use the Document Object Model (DOM)'s InnerHTML property to change the text.

Me.WebSMSView.Document.DomDocument.Body.InnerHTML = text


This doesn't have any side effects as method 1, and is preferable, but requires the use of Reflection in C#, and Option Strict Off in VB.NET

Method 3: Change system sound preferences from code. Disable it when the application has focus and then re-enable when the application closes/loses focus.

WebClickSound.cs: class to enable/disable the click sound

class WebClickSound
{
/// <summary>
/// Enables or disables the web browser navigating click sound.
/// </summary>
public static bool Enabled
{
get
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string keyValue = (string)key.GetValue(null);
return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
}
set
{
string keyValue;

if (value)
{
keyValue = "%SystemRoot%\\Media\\";
if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
{
// XP
keyValue += "Windows XP Start.wav";
}
else if (Environment.OSVersion.Version.Major == 6)
{
// Vista
keyValue += "Windows Navigation Start.wav";
}
else
{
// Don't know the file name so I won't be able to re-enable it
return;
}
}
else
{
keyValue = "\"\"";
}

// Open and set the key that points to the file
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, keyValue, RegistryValueKind.ExpandString);
isEnabled = value;
}
}
}

Main form: use the above code in these 3 events: Activated, Deactivated and FormClosing

private void Form1_Activated(object sender, EventArgs e)
{
// Disable the sound when the program has focus
WebClickSound.Enabled = false;
}

private void Form1_Deactivate(object sender, EventArgs e)
{
// Enable the sound when the program is out of focus
WebClickSound.Enabled = true;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Enable the sound on app exit
WebClickSound.Enabled = true;
}


This works but is probably an overkill for this task.

Reference:

How To Disable WebBrowser ‘Click Sound’ in your app only, http://stackoverflow.com/questions/10456/howto-disable-webbrowser-click-sound-in-your-app-only
Read More »

Monday, February 16, 2009

Multi-line Graphics.MeasureString implementation on .Net CF

If you have ever tried to build a dynamic UI for a .Net Compact Framework application, probably you've had to build adjustable multi-line labels or text-boxes. It's hard to solve because the only supported overload for Graphics.MeasureString on .Net CF is:

public SizeF MeasureString ( string text, Font font )

When you need to resize or position the controls dynamically in runtime, it's very important to know what should be the size, particularly the height of the multi-line label or multi-line text-box. It's the same problem if you're building a new custom control with a complex layout and you need to measure a potential multi-line string.

Having only this overload on .Net CF, we cannot get a multi-line string size because it calculates just the size of a single-line string. If the string is longer than the string, it gets a big SizeF result but as a single-line text.

The only solution here is to implement our own multi-line MeasureString method.
To solve the problem, we'll use the native API DrawText. It will calculate the size of the text according with the uFormat parameter and using the graphics (device context) selected font.

[DllImport("coredll.dll")]
static extern int DrawText(IntPtr hdc, string lpStr, int nCount, ref Rect lpRect, int wFormat);

Additionally, if the control if a text-box, we should use the DT_EDITCONTROL flag and add extra 6 pixels (3 pixels at top and 3 pixels at bottom) to the calculated size.

Remember, if you have an empty string, you'll probably need to force one-line size for your controls.

Read More »

Draw an icon from resource

g_hIcon = (HICON)LoadImage((HINSTANCE)GetModuleHandle(IMAGENAME), MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);

DrawIcon(hdc, left, top, g_hIcon);


IMAGENAME is the name the the current DLL/EXE file. The icon must be created using VS resource editor and its ID set to IDI_ICON1

Read More »

Friday, February 13, 2009

Debug a Windows CE setup DLL

::GetModuleFileName(g_hInstDLL, szName, nSize);
::
MessageBox(hwndParent, szName, _T(""), MB_OK);


where g_hInstDLL is the handle to the loaded module, usually available in the DLL entry point:


BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
//assign the handle here
g_hInstDLL
= (HINSTANCE)hModule;
break;
}
return TRUE;
}


  • Change the setup DLL project properties-> Configuration Properties->Linker -> General -> Output File. Change the existing value to $(OutDir)/STPXXXX.dll where STXXXX.dll is the filename found in step 3 and rebuild the DLL.
  • Go to Tools -> Attach To Process, select device or emulator and attach to process tmarshaller.exe
  • Breakpoint should now be hit and debugging can be done.
  • After debugging, remember to change the linker output file name back to how it was (e.g. $(OutDir)/Setup.dll )

    Reference:

    http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesnative/thread/03b20581-1479-44aa-ba9d-caf1c313c4eb

    Read More »

    Tuesday, February 10, 2009

    VB.NET: Empty string vs. Null Reference

    'If st is an empty string, e.g.:
    Dim st as String = String.Empty

    'The following returns TRUE:
    Dim ok as Boolean = (st = Nothing)

    'But this returns FALSE:
    Dim ok as Boolean = (st is Nothing)


    The "=" operator for String data type in VB.NET treats empty strings and null strings equally whereas the "is" operator treats strings as reference and does not care about the values. An empty string is not a null reference.

    Read More »

    Wednesday, February 4, 2009

    Changing code between VB, C# and other languages

    Some tools are available to convert code between languages:

    Using Telerik Online Code converter, http://www.codechanger.com/
    CodeTranslator, http://www.carlosag.net/Tools/CodeTranslator/
    dotnetspider, www.dotnetspider.com/convert/Vb-To-Csharp.aspx





    Read More »

    Sunday, February 1, 2009

    Reboot a PocketPC/Smartphone from code

    The following code will reboot the device abruptly without giving the user any prompt.


    #define IOCTL_HAL_REBOOT CTL_CODE(FILE_DEVICE_HAL, 15, METHOD_BUFFERED, FILE_ANY_ACCESS)

    extern "C" __declspec(dllimport) BOOL KernelIoControl(DWORD dwIoControlCode, LPVOID lpInBuf, DWORD nInBufSize, LPVOID lpOutBuf, DWORD nOutBufSize, LPDWORD lpBytesReturned);

    //soft reset the device. Return true if OK, false if error

    BOOL ResetDevice()

    {

    return KernelIoControl(IOCTL_HAL_REBOOT, NULL, 0, NULL, 0, NULL);

    }

    Read More »