Wednesday, September 10, 2008
Full Screen featues in Windows mobile.
I look msdn forums last few days,in the forum many guys asked about the full screen features in windows mobile. Since i will post here my code for that.
The full screen features we can do by two ways.
1. We can do simplify in Windows mobile 5.0 or later like hide the menu,give empty text and set widows state is maximized.
2.we can do by the calling P/Invoke.
it's little interesting, because of OS API have a interesting method "SHFullScreen"
So when we pass our current form handle and window states to this method it's done.
before that we must get window handle to for current window.
so sample code below
public class WinAPI
{
internal const int SHFS_SHOWTASKBAR = 0x0001;
internal const int SHFS_HIDETASKBAR = 0x0002;
internal const int SHFS_SHOWSIPBUTTON = 0x0004;
internal const int SHFS_HIDESIPBUTTON = 0x0008;
internal const int SHFS_SHOWSTARTICON = 0x0010;
internal const int SHFS_HIDESTARTICON = 0x0020;
// Code used to hide the Windows bar
[DllImport("aygshell.dll", EntryPoint = "SHFullScreen", SetLastError = true)]
internal static extern bool SHFullScreen(IntPtr hwndRequester, int dwState);
[DllImport("coredll.dll", EntryPoint = "GetForegroundWindow", SetLastError = true)]
internal static extern IntPtr GetForegroundWindow();
[DllImport("coredll.dll")]
public static extern IntPtr GetCapture();
// Code used to hide the Windows bar
public static void FullScreen()
{
IntPtr hwnd = GetForegroundWindow();
SHFullScreen(hwnd, SHFS_HIDETASKBAR);
}
}
that's all
thank you
Thursday, September 4, 2008
Hi How to use the System State in Windows mobile
here simple sample how to use the system state class in windows mobile.
Question: How to check the cradlepresent in the Windows mobile Device or Emulator ?
Answers:
SystemState cradleState = null;
private void Init()
{
cradleState = new SystemState(SystemProperty.CradlePresent);
cradleState.Changed += new ChangeEventHandler(cradleState_Changed);
}
void cradleState_Changed(object sender, ChangeEventArgs args)
{
bool isPresent =Convert.ToBoolean(SystemState.GetValue(SystemProperty.CradlePresent));
if (isPresent)
{
MessageBox.Show("Present");
}
}
thank you
All System States in WIndows mobile
see here list of all System states.
using System;
namespace Microsoft.WindowsMobile.Status
{
// Summary:
// Specifies the device-wide system properties
public enum SystemProperty
{
// Summary:
// Gets the name of the application that was previously active and the name
// of the application that is currently active, separated by the 'Escape' character
// ('\e').
ActiveApplication = 0,
//
// Summary:
// Gets the orientation of the display, specified as the number of degrees,
// ranging from 0 to 360. Portrait = 0. Landscape = 90 or -90.
DisplayRotation = 1,
//
// Summary:
// Gets a value indicating whether a keyboard is attached and enabled.
KeyboardPresent = 2,
//
// Summary:
// Gets a value indicating whether the device is connected to a cradle.
CradlePresent = 3,
//
// Summary:
// Gets a value indicating whether a camera is attached and enabled.
CameraPresent = 4,
//
// Summary:
// Gets the number of unread SMS messages.
MessagingSmsUnread = 5,
//
// Summary:
// Gets the number of unread MMS messages
MessagingMmsUnread = 6,
//
// Summary:
// Gets the number of unplayed voice mail messages.
MessagingVoiceMailTotalUnread = 7,
//
// Summary:
// Gets the number of unplayed voice mail messages for line 1.
MessagingVoiceMail1Unread = 8,
//
// Summary:
// Gets the number of unplayed voice mail messages for line 2
MessagingVoiceMail2Unread = 9,
//
// Summary:
// Gets the number of unread ActiveSync e-mail messages.
MessagingActiveSyncEmailUnread = 10,
//
// Summary:
// Gets the total number of unread e-mail messages from all POP3/IMAP accounts.
MessagingTotalEmailUnread = 11,
//
// Summary:
// Gets the number of unread e-mail messages from all non-ActiveSync messaging
// accounts.
MessagingOtherEmailUnread = 12,
//
// Summary:
// Gets the name of the e-mail account that was last active.
MessagingLastEmailAccountName = 13,
//
// Summary:
// Gets the name of the SMS messaging account.
MessagingSmsAccountName = 14,
//
// Summary:
// Gets the name of the MMS messaging account.
MessagingMmsAccountName = 15,
//
// Summary:
// Get the name of the Outlook e-mail messaging account.
MessagingActiveSyncAccountName = 16,
//
// Summary:
// Gets the number of active tasks.
TasksActive = 17,
//
// Summary:
// Gets the number of high priority tasks that are currently active.
TasksHighPriority = 18,
//
// Summary:
// Gets the number of active tasks that are due today.
TasksDueToday = 19,
//
// Summary:
// Gets the number of overdue tasks.
TasksOverdue = 20,
//
// Summary:
// Gets the subject of the next Appointment.
CalendarNextAppointmentSubject = 21,
//
// Summary:
// Gets the location of the next Appointment.
CalendarNextAppointmentLocation = 22,
//
// Summary:
// Gets the starting time of the next Appointment.
CalendarNextAppointmentStart = 23,
//
// Summary:
// Gets the ending time of the next Appointment.
CalendarNextAppointmentEnd = 24,
//
// Summary:
// Gets the album artist's name of the currently playing track in Windows Media
// Player.
MediaPlayerAlbumArtist = 25,
//
// Summary:
// Gets the title of the track currently playing in Windows Media Player. For
// example, "128Kbps"
MediaPlayerTrackBitrate = 26,
//
// Summary:
// Gets the title of the track currently playing in Windows Media Player.
MediaPlayerTrackTitle = 27,
//
// Summary:
// Gets the album title of the currently playing track in Windows Media Player.
MediaPlayerAlbumTitle = 28,
//
// Summary:
// Gets the artist's name of the currently playing track in Windows Media Player.
MediaPlayerTrackArtist = 29,
//
// Summary:
// Gets the number of the current track playing in Windows Media Player.
MediaPlayerTrackNumber = 30,
//
// Summary:
// Gets the genre of the currently playing track in Windows Media Player.
MediaPlayerTrackGenre = 31,
//
// Summary:
// Gets the elapsed time (in milliseconds) of the currently playing track in
// Windows Media Player.
MediaPlayerTrackTimeElapsed = 32,
//
// Summary:
// Gets the remaining battery power level, expressed as a percentage of fully
// charged.
PowerBatteryStrength = 33,
//
// Summary:
// Gets the current battery state (for example, it is low, and charging). This
// enumeration allows a bitwise combination of its member values.
PowerBatteryState = 34,
//
// Summary:
// Gets the remaining backup battery power level, expressed as a percentage
// of fully charged.
PowerBatteryBackupStrength = 35,
//
// Summary:
// Gets the current backup battery state (for example, it is low, and charging).
// This enumeration allows a bitwise combination of its member values.
PowerBatteryBackupState = 36,
//
// Summary:
// Gets the current time. This Date/Time value updates once per minute.
Time = 37,
//
// Summary:
// Gets the current date. This Date/Time value changes once per day. Monitor
// this property to perform actions on a daily basis. Note: Do not use Date
// to get an accurate clock time; instead, use Time.
Date = 38,
//
// Summary:
// Get the phone signal strength, expressed as a percentage of full strength.
PhoneSignalStrength = 39,
//
// Summary:
// Gets the name of the mobile operator (i.e., the mobile phone company, or
// carrier).
PhoneOperatorName = 40,
//
// Summary:
// Gets the name of the person you are talking to on the phone. This value is
// not set when you are talking on a conference call.
PhoneTalkingCallerName = 41,
//
// Summary:
// Gets the number of active phone calls.
PhoneActiveCallCount = 42,
//
// Summary:
// Gets the localized name of the current sound profile. (Smartphone only)
PhoneProfileName = 43,
//
// Summary:
// Gets the non-localized name of the current sound profile. For example, "Normal",
// "Silent", "Car", "Headset", "Loud", "Meeting", or "Speakerphone". (Smartphone
// only)
PhoneProfile = 44,
//
// Summary:
// Gets the cell broadcast message
PhoneCellBroadcast = 45,
//
// Summary:
// Gets a value indicating whether there is a conflict with the next Appointment.
CalendarNextAppointmentHasConflict = 46,
//
// Summary:
// Gets the mobile device owner's name.
OwnerName = 47,
//
// Summary:
// Gets the mobile device owner's phone number.
OwnerPhoneNumber = 48,
//
// Summary:
// Gets the mobile device owner's e-mail address.
OwnerEmail = 49,
//
// Summary:
// Gets the text notes entered by the owner of the mobile device.
OwnerNotes = 50,
//
// Summary:
// Gets ActiveSync's current synchronization state.
ActiveSyncStatus = 51,
//
// Summary:
// Gets the number of missed phone calls.
PhoneMissedCalls = 52,
//
// Summary:
// Gets a value indicating whether a headset is present
HeadsetPresent = 53,
//
// Summary:
// Gets a value indicating whether a car kit is present
CarKitPresent = 54,
//
// Summary:
// Gets a value indicating whether the speakerphone is active
SpeakerPhoneActive = 55,
//
// Summary:
// Gets a value indicating whether the phone supports multiple lines.
PhoneMultiLine = 56,
//
// Summary:
// Gets a value indicating whether the Subscriber Identity Module (SIM) memory
// is full.
PhoneSimFull = 57,
//
// Summary:
// Gets a value indicating whether the Subscriber Identity Module (SIM) is installed
// in the mobile device.
PhoneNoSim = 58,
//
// Summary:
// Gets a value indicating whether the Subscriber Identity Module (SIM) is invalid.
PhoneInvalidSim = 59,
//
// Summary:
// Gets a value indicating whether the Subscriber Identity Module (SIM) is blocked.
PhoneBlockedSim = 60,
//
// Summary:
// Gets a value indicating whether the phone's radio is turned off.
PhoneRadioOff = 61,
//
// Summary:
// Gets a value indicating whether the mobile device has a phone.
PhoneRadioPresent = 62,
//
// Summary:
// Gets a value indicating whether the phone's ringer is off (i.e., if it rings
// and/or vibrates).
PhoneRingerOff = 63,
//
// Summary:
// Gets a value indicating whether line 1 is selected.
PhoneLine1Selected = 64,
//
// Summary:
// Gets a value indicating whether line 2 is selected.
PhoneLine2Selected = 65,
//
// Summary:
// Gets a value indicating whether the phone is currently in roaming mode.
PhoneRoaming = 66,
//
// Summary:
// Gets a value indicating whether call forwarding is enabled on line 1.
PhoneCallForwardingOnLine1 = 67,
//
// Summary:
// Gets a value indicating whether there was a new missed call.
PhoneMissedCall = 68,
//
// Summary:
// Gets a value indicating whether the phone has an active cellular data connection.
PhoneActiveDataCall = 69,
//
// Summary:
// Gets a value indicating whether the call barring feature is enabled.
PhoneCallBarring = 70,
//
// Summary:
// Gets a value indicating whether a phone call is currently on hold.
PhoneCallOnHold = 71,
//
// Summary:
// Gets a value indicating whether a conference call is currently in progress.
PhoneConferenceCall = 72,
//
// Summary:
// Gets a value indicating whether there is an incoming (ringing) call.
PhoneIncomingCall = 73,
//
// Summary:
// Gets a value indicating whether the phone is currently attempting to connect
// an outgoing call.
PhoneCallCalling = 74,
//
// Summary:
// Gets a value indicating whether the phone currently has GPRS coverage.
PhoneGprsCoverage = 75,
//
// Summary:
// Gets a value indicating whether the phone is not currently connected to a
// network.
PhoneNoService = 76,
//
// Summary:
// Gets a value indicating whether the phone is currently searching for service
// on a network.
PhoneSearchingForService = 77,
//
// Summary:
// Gets a value indicating whether the phone is currently registered on its
// home network.
PhoneHomeService = 78,
//
// Summary:
// Gets a value indicating whether the phone currently has 1xRTT coverage.
Phone1xRttCoverage = 79,
//
// Summary:
// Gets a value indicating whether there is currently a phone call in the talking
// state.
PhoneCallTalking = 80,
//
// Summary:
// Gets a value indicating whether call forwarding is currently active on line
// 2.
PhoneCallForwardingOnLine2 = 81,
//
// Summary:
// Gets the next Appointment.
CalendarNextAppointment = 82,
//
// Summary:
// Gets the user's availability (e.g., Free, Busy, Tenative, Out of Office)
// status for the next Appointment.
CalendarNextAppointmentBusyStatus = 83,
//
// Summary:
// Gets the next Appointment's categories.
CalendarNextAppointmentCategories = 84,
//
// Summary:
// Gets the current Appointment.
CalendarAppointment = 85,
//
// Summary:
// Gets the current Appointment's subject.
CalendarAppointmentSubject = 86,
//
// Summary:
// Gets the current Appointment's location.
CalendarAppointmentLocation = 87,
//
// Summary:
// Gets the current Appointment's starting time.
CalendarAppointmentStartTime = 88,
//
// Summary:
// Gets the current Appointment's ending time.
CalendarAppointmentEndTime = 89,
//
// Summary:
// Gets a value indicating whether the current Appointment has a scheduling
// conflict with an existing Appointment.
CalendarAppointmentHasConflict = 90,
//
// Summary:
// Gets the user's availability (free/busy status) for the time-slot taken by
// the current Appointment.
CalendarAppointmentBusyStatus = 91,
//
// Summary:
// Gets the current Appointment's categories.
CalendarAppointmentCategories = 92,
//
// Summary:
// Gets the Appointment that is currently displayed on the Home Screen.
CalendarHomeScreenAppointment = 93,
//
// Summary:
// Gets the subject of the Appointment that is currently displayed on the Home
// Screen.
CalendarHomeScreenAppointmentSubject = 94,
//
// Summary:
// Gets the location of the Appointment that is currently displayed on the Home
// Screen.
CalendarHomeScreenAppointmentLocation = 95,
//
// Summary:
// Gets the starting time of the Appointment that is currently displayed on
// the Home Screen.
CalendarHomeScreenAppointmentStartTime = 96,
//
// Summary:
// Gets the ending time of the Appointment that is currently displayed on the
// Home Screen.
CalendarHomeScreenAppointmentEndTime = 97,
//
// Summary:
// Gets a value indicating whether the Appointment that is currently displayed
// on the Home Screen has a scheduling conflict.
CalendarHomeScreenAppointmentHasConflict = 98,
//
// Summary:
// Gets the user's availability (free/busy status) for the Appointment displayed
// on the Home Screen.
CalendarHomeScreenAppointmentBusyStatus = 99,
//
// Summary:
// Gets the categories of the Appointment that is currently displayed on the
// Home Screen.
CalendarHomeScreenAppointmentCategories = 100,
//
// Summary:
// Gets the name of the person who is currently placing the incoming call.
PhoneIncomingCallerName = 101,
//
// Summary:
// Gets the name of the last caller to place an incoming call.
PhoneLastIncomingCallerName = 102,
//
// Summary:
// Gets the incoming call's phone number (Caller ID).
PhoneIncomingCallerNumber = 103,
//
// Summary:
// Gets the last incoming call's phone number (Caller ID).
PhoneLastIncomingCallerNumber = 104,
//
// Summary:
// Gets the name of the property that matches the Caller ID, e.g. "h" for "Home
// Telephone".
PhoneIncomingCallerContactPropertyName = 105,
//
// Summary:
// Gets the name of the property that matches the last Caller ID, e.g. "h" for
// "Home Telephone".
PhoneLastIncomingCallerContactPropertyName = 106,
//
// Summary:
// Gets the CEPROPID of the property that matches the Caller ID, for example,
// PIMPR_HOME_TELEPHONE_NUMBER.
PhoneIncomingCallerContactPropertyID = 107,
//
// Summary:
// Gets the CEPROPID of the property that matches the last Caller ID, for example,
// PIMPR_HOME_TELEPHONE_NUMBER.
PhoneLastIncomingCallerContactPropertyID = 108,
//
// Summary:
// Gets the Contact that matches the Caller ID.
PhoneIncomingCallerContact = 109,
//
// Summary:
// Gets the Contact that matches the last Caller ID.
PhoneLastIncomingCallerContact = 110,
//
// Summary:
// Gets the currently connected caller's phone number.
PhoneTalkingCallerNumber = 111,
//
// Summary:
// Gets the name of the property of the contact who is on the active phone call,
// e.g. "h" for "Home Telephone".
PhoneTalkingCallerContactPropertyName = 112,
//
// Summary:
// Gets the CEPROPID of the property of the contact who is on the active phone
// call, for example, PIMPR_HOME_TELEPHONE_NUMBER.
PhoneTalkingCallerContactPropertyID = 113,
//
// Summary:
// Gets the contact who is on the active phone call.
PhoneTalkingCallerContact = 114,
//
// Summary:
// Gets a value indicating the number of connections that are currently connected.
ConnectionsCount = 115,
//
// Summary:
// Gets a value indicating the number of Bluetooth connections that are currently
// connected.
ConnectionsBluetoothCount = 116,
//
// Summary:
// Gets a semicolon delimited string containing the description of each of the
// Bluetooth connections.
ConnectionsBluetoothDescriptions = 117,
//
// Summary:
// Gets a value indicating the number of cellular connections that are currently
// connected.
ConnectionsCellularCount = 118,
//
// Summary:
// Gets a semicolon delimited string containing the description of each cellular
// connection.
ConnectionsCellularDescriptions = 119,
//
// Summary:
// Gets a value indicating the number of network connections that are currently
// connected.
ConnectionsNetworkCount = 120,
//
// Summary:
// Gets a semicolon delimited string containing the description of each network
// connection.
ConnectionsNetworkDescriptions = 121,
//
// Summary:
// Gets a semicolon delimited string containing the adapter name of each network
// connection.
ConnectionsNetworkAdapters = 122,
//
// Summary:
// Gets a value indicating the number of desktop connections that are currently
// connected.
ConnectionsDesktopCount = 123,
//
// Summary:
// Gets a semicolon delimited string containing the description of each desktop
// connection.
ConnectionsDesktopDescriptions = 124,
//
// Summary:
// Gets a value indicating the number of network connections that are currently
// connected.
ConnectionsProxyCount = 125,
//
// Summary:
// Gets a semicolon delimited string containing the description of each proxy
// connection.
ConnectionsProxyDescriptions = 126,
//
// Summary:
// Gets a value indicating the number of modem connections that are currently
// connected.
ConnectionsModemCount = 127,
//
// Summary:
// Gets a semicolon delimited string containing the description of each modem
// connection.
ConnectionsModemDescriptions = 128,
//
// Summary:
// Gets a value indicating the number of connections of unknown type that are
// currently connected.
ConnectionsUnknownCount = 129,
//
// Summary:
// Gets a semicolon delimited string containing the description of each connections
// of unknown type.
ConnectionsUnknownDescriptions = 130,
//
// Summary:
// Gets a value indicating the number of virtual private network connections
// that are currently connected.
ConnectionsVpnCount = 131,
//
// Summary:
// Gets a semicolon delimited string containing the description of each virtual
// private network connection.
ConnectionsVpnDescriptions = 132,
//
// Summary:
// Gets the current "All Day Event" Appointment.
CalendarEvent = 133,
//
// Summary:
// Gets the subject of the current "All Day Event" Appointment.
CalendarEventSubject = 134,
//
// Summary:
// Gets the location of the current "All Day Event" Appointment.
CalendarEventLocation = 135,
//
// Summary:
// Gets the starting time of the current "All Day Event" Appointment. This will
// be the starting day of an Appointment Event that spans multiple days.
CalendarEventStartTime = 136,
//
// Summary:
// Gets the ending time of the current "All Day Event" Appointment. This will
// be the starting day of an Appointment Event that spans multiple days.
CalendarEventEndTime = 137,
//
// Summary:
// Gets a value indicating whether the user's availability (free/busy) status
// conflicts with the current "All Day Event".
CalendarEventHasConflict = 138,
//
// Summary:
// Gets the user's availability (free/busy status) for the current "All Day
// Event".
CalendarEventBusyStatus = 139,
//
// Summary:
// Gets the categories for the current "All Day Event".
CalendarEventCategories = 140,
}
}
thank you
Tuesday, July 22, 2008
Get List of threads in Windows MObile.
it's another nice good morning, because of when i look MS forums last night, one guy asked , how can get list of threads in .net CF. then i tried work out in my home. then it's come sounds is good.
Here code for you.
first i want to create threadentry32 structure.
class THREADENTRY32
{
public uint cntUsage;
public uint dwFlags;
public uint dwSize;
public uint th32AccessKey;
public uint th32CurrentProcessID;
public uint th32OwnerProcessID;
public uint th32ThreadID;
public int tpBasePri;
public int tpDeltaPri;
public THREADENTRY32()
{
}
public THREADENTRY32(byte[] aData)
{
this.dwSize = BitConverter.ToUInt32(aData, 0);
this.cntUsage = BitConverter.ToUInt32(aData, 4);
this.th32ThreadID =BitConverter.ToUInt32(aData, 8);
this.th32OwnerProcessID = BitConverter.ToUInt32(aData, 12);
this.tpBasePri = BitConverter.ToInt32(aData, 0x10);
this.tpDeltaPri = BitConverter.ToInt32(aData, 0x18);
this.dwFlags = BitConverter.ToUInt32(aData, 0x20);
this.th32AccessKey = BitConverter.ToUInt32(aData, 0x24);
this.th32CurrentProcessID = BitConverter.ToUInt32(aData, 40);
}
public byte[] ToByteArray()
{
byte[] aData = new byte[0x2c];
Util.SetUInt(aData, 0, 0x2c);
return aData;
}
}
then i want to get snapshot for thread collections.
if i want to get thread snapshot olny , flag should be 4.
[DllImport("toolhelp.dll", EntryPoint = "CreateToolhelp32Snapshot", SetLastError = true)]
private static extern IntPtr CreateToolhelp32SnapshotAPI(uint flags, uint processid);
[DllImport("toolhelp.dll", EntryPoint = "CloseToolhelp32Snapshot", SetLastError = true)]
private static extern int CloseToolhelp32SnapshotAPI(IntPtr handle);
[DllImport("toolhelp.dll", EntryPoint = "Thread32First", SetLastError = true)]
private static extern int Thread32FirstAPI(IntPtr handle, byte[] te);
[DllImport("toolhelp.dll", EntryPoint = "Thread32Next", SetLastError = true)]
private static extern int Thread32NextAPI(IntPtr handle, byte[] te);
public static THREADENTRY32[] GetThreads(uint processID)
{
ArrayList list = new ArrayList();
IntPtr handle = CreateToolhelp32Snapshot(4, processID);
if (((int) handle) <= 0)
{
throw new Exception("Unable to create snapshot");
}
try
{
byte[] te = new THREADENTRY32().ToByteArray();
for (int i = Thread32First(handle, te); i == 1; i = Thread32Next(handle, te))
{
THREADENTRY32 threadentry = new THREADENTRY32(te);
if ((processID == 0) || (threadentry.th32OwnerProcessID == processID))
{
THREADENTRY32entry = new THREADENTRY32(threadentry);
list.Add(entry);
}
}
}
catch (Exception exception)
{
throw new Exception("Exception: " + exception.Message);
}
CloseToolhelp32Snapshot(handle);
return (THREADENTRY32[]) list.ToArray(typeof(THREADENTRY32));
}
That's all
try and give a feedback.
Saturday, July 19, 2008
Gradient Button in Windows mobile.
Again in this post series, today gradient button in windows mobile with managed code.
it's pretty simple,and when are finished it's look cool and nice.
i had posted my article in the www.codeproject.com
here link for you all.
http://www.codeproject.com/KB/mobile/Gradient_bt_NETCF.aspx
Enjoy .
Wednesday, July 16, 2008
Get IP address in Windows MObile
Get IP address of the device, when they connected to network.
private void GetMyIP()
{
IPHostEntry hostentry = Dns.GetHostEntry(Dns.GetHostName());
if (hostentry != null)
{
IPAddress[] collectionOfIPs = hostentry.AddressList;
MessageBox.Show(collectionOfIPs[0].ToString());
}
}
Thank you
Tuesday, July 15, 2008
Gradient BackGround in Windows mobile
Another cool stuff in this series, how make to gradient background in Windows mobile device forms?.
MSDN have answer for above question. because of .NET CF haven't support directly draw Gradient Background, but Win CE API Have support, so we can play with P/Invoke, can make a cool and pretty background.
Just Sample here
http://msdn.microsoft.com/en-us/library/ms229655.aspx
Thank you
Load Image to PictureBox in Windows Mobile
Another cool stuff, many guys, asking in MS forums, how load the image to picture box from the device directory. it's pretty easy, there have many ways.
1.loan image directly from the location
2. load the image from the memory stream.
So here code for you
1.
pictureBox.Image = new Bitmap (“Full.Path.To.Bitmpap.”);
2.
private void LoadImage(string filePath)
{
using (FileStream reader = new FileStream(filePath, FileMode.Open))
{
byte[] data = new byte[reader.Length];
reader.Read(data, 0, (int)reader.Length);
using (MemoryStream memory = new MemoryStream(data))
{
pictureBox1.Image = new Bitmap(memory);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
}
Thank you
Transparent Label in .NET Compact framework
I seen in MS forums lof of guys, asking how to make transparent label.
it's pretty simple, when we use the Graphics object in .NET CF.
Here complete code for create transparent label.
private void DrawLabel (Label label, Graphics gfx)
{
if (label.TextAlign == ContentAlignment.TopLeft)
{
gfx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), label.Bounds);
}
else if (label.TextAlign == ContentAlignment.TopCenter)
{
SizeF size = gfx.MeasureString(label.Text, label.Font);
float left = ((float) this.Width + label.Left) / 2 - size.Width / 2;
RectangleF rect = new RectangleF(left, (float) label.Top, size.Width, label.Height);
gfx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), rect);
}
else //is aligned at TopRight
{
SizeF size = gfx.MeasureString(label.Text, label.Font);
float left = (float) label.Width - size.Width + label.Left;
RectangleF rect = new RectangleF(left, (float) label.Top, size.Width, label.Height);
gfx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), rect);
}
}
Thank you
How to find string within ComboBox in .NET CF
The comapct framework haven't method for find a string within combobox, but native code have support. So little P/Invoke and get tht features to .NET CF
Here code for you.
public const int CB_FINDSTRINGEXACT = 0x0158;
[DllImport("coredll.dll")]
internal static extern int SendMessage(IntPtr hWnd, int msg, int wParam, string lParam);
private void FindStringExact(string find)
{
int m = SendMessage(comboBox1.Handle, CB_FINDSTRINGEXACT, 0, find + "\0");
if (m > 0)
{
MessageBox.Show(find);
}
else
{
MessageBox.Show("no");
}
}
Thank you
How to create Action Lable in .Net compact framework.
Now i'm back in my blog, so i have plan post some cool stuff in my blog every day.
According that, today i will post a code for , how to create Action Lable in .NETCF.
It's pretty simple, Because of we dont need play with P/Invoke. but we want to play with GDI.
Because of i want to create a graphical objects,
Here complete code for you.
using System;
using System.Windows.Forms;
using System.Drawing;
namespace RaveSoftBlog
{
///
/// Arrow label button control.
///
public class ActionLabel : Control
{
class Const
{
public static Color DisableColor = Color.FromArgb(150,150,80);
public static Color PushedColor = Color.FromArgb(160,100,0);
public static Color ForeColor = Color.FromArgb(90,90,45);
public static Color BulletColor = Color.FromArgb(180,180,110);
public const string FontName = "Arial";
public const int FontSize = 10;
public const int BulletSize = 8;
}
// internal fields
bool m_pushed;
Rectangle m_rcHitArea;
Point[] m_bulletPts;
// gdi objects
Bitmap m_bmp;
Font m_font;
Pen m_penPushed, m_penFore, m_penDisabled;
Brush m_brushPushed, m_brushFore, m_brushDisabled;
// ctor
public ActionLabelControl()
{
// colors
this.ForeColor = Const.ForeColor;
// gdi objects
CreateGdiObjects();
}
protected override void OnPaint(PaintEventArgs e)
{
// draw to memory bitmap
CreateMemoryBitmap(e.Graphics);
Graphics g = Graphics.FromImage(m_bmp);
DrawLabel(g);
// blit memory bitmap to screen
e.Graphics.DrawImage(m_bmp, 0, 0);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// don't pass to base since we paint everything, avoid flashing
}
protected override void OnEnabledChanged(EventArgs e)
{
// redraw when enabled state changes
Invalidate();
}
// draw label and arrow
private void DrawLabel(Graphics g)
{
// background
g.Clear(Parent.BackColor);
// determine what pen and brush to use
Pen pen = m_pushed ? m_penPushed :
(this.Enabled ? m_penFore : m_penDisabled);
Brush brush = m_pushed ? m_brushPushed :
(this.Enabled ? m_brushFore : m_brushDisabled);
// draw solid arrow if enabled
if (this.Enabled)
g.FillPolygon(brush, m_bulletPts);
g.DrawPolygon(pen, m_bulletPts);
// label text
Size textSize = g.MeasureString(Text, m_font).ToSize();
g.DrawString(Text, m_font, brush,
Const.BulletSize+8, (this.Height - textSize.Height)/2);
}
protected override void OnMouseDown (MouseEventArgs e)
{
base.OnMouseDown(e);
this.Capture = true;
// see if clicked on label text or arrow
if (m_rcHitArea.Contains(e.X, e.Y))
{
m_pushed = true;
Invalidate();
}
}
protected override void OnMouseUp (MouseEventArgs e)
{
base.OnMouseUp(e);
this.Capture = false;
m_pushed = false;
Invalidate();
}
protected override void OnClick(EventArgs e)
{
if (m_pushed)
base.OnClick(e);
}
private void CreateGdiObjects()
{
// gdi objects
m_font = new Font(Const.FontName, Const.FontSize, FontStyle.Bold);
m_penPushed = new Pen(Const.PushedColor);
m_penFore = new Pen(this.ForeColor);
m_penDisabled = new Pen(Const.DisableColor);
m_brushPushed = new SolidBrush(Const.PushedColor);
m_brushFore = new SolidBrush(this.ForeColor);
m_brushDisabled = new SolidBrush(Const.DisableColor);
}
private void CreateMemoryBitmap(Graphics g)
{
// see if need to create gdi objects
if (m_bmp == null || m_bmp.Width != this.Width || m_bmp.Height != this.Height)
{
// memory bitmap
m_bmp = new Bitmap(this.Width, this.Height);
// bullet points
int halfHeight = this.Height/2;
m_bulletPts = new Point[3];
m_bulletPts[0] = new Point(0, halfHeight-(Const.BulletSize/2));
m_bulletPts[1] = new Point(Const.BulletSize, halfHeight);
m_bulletPts[2] = new Point(0, halfHeight+(Const.BulletSize/2));
// hit area
Size textSize = g.MeasureString(Text, m_font).ToSize();
m_rcHitArea = new Rectangle(0,
(this.Height - textSize.Height)/2,
textSize.Width + Const.BulletSize + 8,
textSize.Height);
}
}
}
}
Thank you
System Center Mobile device
Another good news, the Microsoft lounge the new blog for SCMD.
i hope it's help to mobile related developer with MS.
http://blogs.technet.com/scmdm/
Thank you
Wednesday, January 9, 2008
Use the Sync Framework with C#
Hi Guys
Micro soft introduce new framework for all type sync. This framework have varity type of the specify sync operation with database or filesystem.
List of those are,
1.ADO.Net
2.Common(File System)
You can downlaod SyncFramework from bellow url
The Sync framework have managed class libraries. So we can code with C# or other your desired language (MS).
After download and installed , create a new Project with C# or your desired language.
I had create console application with C#
Afte you must add References Microsoft Synchronization
using System;
using System.IO;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Files;
public class FileSyncProviderSample
{
public static void Main( string [] args)
{
if (args.Length <>
string .IsNullOrEmpty(args[0]) || string .IsNullOrEmpty(args[1]) ||
! Directory .Exists(args[0]) || ! Directory .Exists(args[1]))
{
Console .WriteLine(
"Usage: FileSyncSample [valid directory path 1] [valid directory path 2]" );
return ;
}
string replica1RootPath = args[0];
string replica2RootPath = args[1];
string idFileName = "filesync.id" ;
SyncId replica1Id = GetReplicaId( Path .Combine(args[0], idFileName));
SyncId replica2Id = GetReplicaId( Path .Combine(args[1], idFileName));
try
{
// Set options for the sync operation
FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
FileSyncOptions.RecycleDeletes | FileSyncOptions.RecycleOverwrites;
FileSyncScopeFilter filter = new FileSyncScopeFilter();
filter.FileNameExcludes.Add(idFileName); // Exclude the id file
// Explicitly detect changes on both replicas upfront, to avoid two change
// detection passes for the two-way sync
DetectChangesOnFileSystemReplica(
replica1Id, replica1RootPath, filter, options);
DetectChangesOnFileSystemReplica(
replica2Id, replica2RootPath, filter, options);
// Sync in both directions
SyncFileSystemReplicasOneWay(replica1Id, replica2Id,
replica1RootPath, replica2RootPath, filter, options);
SyncFileSystemReplicasOneWay(replica2Id, replica1Id,
replica2RootPath, replica1RootPath, filter, options);
}
catch ( Exception e)
{
Console .WriteLine( "\nException from File System Provider:\n" + e.ToString());
}
}
public static void DetectChangesOnFileSystemReplica(
SyncId replicaId, string replicaRootPath,
FileSyncScopeFilter filter, FileSyncOptions options)
{
FileSyncProvider provider = null ;
try
{
provider = new FileSyncProvider(replicaId, replicaRootPath, filter, options);
provider.DetectChanges();
}
finally
{
// Release resources
if (provider != null )
provider.Dispose();
}
}
public static void SyncFileSystemReplicasOneWay(
SyncId sourceReplicaId, SyncId destinationReplicaId,
string sourceReplicaRootPath, string destinationReplicaRootPath,
FileSyncScopeFilter filter, FileSyncOptions options)
{
FileSyncProvider sourceProvider = null ;
FileSyncProvider destinationProvider = null ;
try
{
sourceProvider = new FileSyncProvider(
sourceReplicaId, sourceReplicaRootPath, filter, options);
destinationProvider = new FileSyncProvider(
destinationReplicaId, destinationReplicaRootPath, filter, options);
destinationProvider.AppliedChange +=
new EventHandler
destinationProvider.SkippedChange +=
new EventHandler
SyncAgent agent = new SyncAgent();
agent.LocalProvider = sourceProvider;
agent.RemoteProvider = destinationProvider;
agent.Direction = SyncDirection.Upload; // Sync source to destination
Console .WriteLine( "Synchronizing changes to replica: " +
destinationProvider.RootDirectoryPath);
agent.Synchronize();
}
finally
{
// Release resources
if (sourceProvider != null ) sourceProvider.Dispose();
if (destinationProvider != null ) destinationProvider.Dispose();
}
}
public static void OnAppliedChange( object sender, AppliedChangeEventArgs args)
{
switch (args.ChangeType)
{
case ChangeType.Create:
Console .WriteLine( "-- Applied CREATE for file " + args.NewFilePath);
break ;
case ChangeType.Delete:
Console .WriteLine( "-- Applied DELETE for file " + args.OldFilePath);
break ;
case ChangeType.Overwrite:
Console .WriteLine( "-- Applied OVERWRITE for file " + args.OldFilePath);
break ;
case ChangeType.Rename:
Console .WriteLine( "-- Applied RENAME for file " + args.OldFilePath +
" as " + args.NewFilePath);
break ;
}
}
public static void OnSkippedChange( object sender, SkippedChangeEventArgs args)
{
Console .WriteLine( "-- Skipped applying " + args.ChangeType.ToString().ToUpper()
+ " for " + (! string .IsNullOrEmpty(args.CurrentFilePath) ?
args.CurrentFilePath : args.NewFilePath) + " due to error" );
if (args.Exception != null )
Console .WriteLine( " [" + args.Exception.Message + "]" );
}
public static SyncId GetReplicaId( string idFilePath)
{
SyncId replicaId = null ;
if ( File .Exists(idFilePath))
{
using ( StreamReader sr = File .OpenText(idFilePath))
{
string strGuid = sr.ReadLine();
if (! string .IsNullOrEmpty(strGuid))
replicaId = new SyncId( new Guid (strGuid));
}
}
if (replicaId == null )
{
using ( FileStream idFile = File .Open(
idFilePath, FileMode .OpenOrCreate, FileAccess .ReadWrite))
{
using ( StreamWriter sw = new StreamWriter (idFile))
{
replicaId = new SyncId( Guid .NewGuid());
sw.WriteLine(replicaId.GetGuidId().ToString( "D" ));
}
}
}
return replicaId;
}
}
basically sync framework work GUID as references. Because of Sync is time depend operation,so we must need a unique id for identification our file/DB is changed , removed and etc.
Con
The SyncFramework had greate feature for sync operation to all types of operation.
You can use the Sync framework for Database Sync , File System Sync,And Mobile decvice File Sync.
More from
http://msdn2.microsoft.com/en-us/sync/default.aspx
http://msdn2.microsoft.com/en-us/sync/bb887623.aspx
Best Regards
RRave