You are browsing the archive for Software development.

by nd4spd

I'm back…with more development!

3:52 am in Software development, Windows Mobile by nd4spd

I haven’t been on here a while and I apologize for that. This summer has been a busy one for me – first in summer school for AP Macroeconomics for 6 weeks and then I went back to India for 4 weeks. I’m back now and of course, school starts in 2 days. But I have been doing some WinMo stuff over the past 2 months. However, I haven’t been working on my OnDemand customization. Instead, something bigger has caught my attention.

Ever since Da_G over at XDA-Developers created a thread about the Image Update system, I’ve been following and developing some of my own software. For those who don’t know, the Image Update system allows for you to update the IMGFS and XIP partition of your phone via cab files instead of flashing the device and losing all personal data/installed applications. To make this mechanism work, which has been present in Windows Mobile since WM5, all of the DSMs (Device Side Manifests) need to be in the proper MS format. Unfortunately, all of the current kitchen tools that we use for ROMs malform these DSMs or completely remove them from the ROMs. Because of that, I’ve been working on applications that will make Image Update work properly. In June, I was able to create two applications – one that regenerated DSMS from scratch in the exact same way MS’s tools are supposed to work. The other would create the Image Update packages and sign them - they produce the same results as the ones generated my MS’s tools as well. I’ve been working to consolidate them into one app that will also act as a ROM kitchen that adheres to MS’s documentation (for the most part :D).

For those who are interested, you can check out Da_G’s thread in the Dev & Hacking section of XDA (I’m too lazy to link to it right now :D)

Getting started with widgets on Windows Mobile 6.5

11:41 am in How To, Software development, Windows Mobile by buzz_lightyear

Now that the Windows Mobile 6.5 resource kit is out (You can download it from here) it is time to start writing widgets!!!

Necessary equipment

  1. The 6.5 emulator images
  2. The web development environment of choice
  3. WMDC or Windows mobile device center (on vista or windows 7) or ActiveSync 4.5

With that you should be ready to go to get started, the first step is to start the emulator and cradle the device. The emulators can be started from the start menu under the “Windows Mobile 6 SDK -> Stand Alone Emulator Images -> ”. The device emulator manager can be started using explorer to navigate to the following folder “C:\Program Files\Microsoft Device Emulator\1.0” and selecting dvcemumanager.exe.

Once they are both started, open WMDC or ActiveSync and select connection options and, on the “Connect one of the following” combo box select “DMA” and click “OK”.

Now, on the “Device Emulator Manager” select “Refresh” and then find the emulator on the list, should be the GUID under others and right click -> cradle to connect it to the PC.

Once that is done, select “Connect without setting up my device” and you should be ready to go, to test, open internet explorer on the 6.5 emulator and navigate to any site, if all is set up correctly it will navigate to it using our brand new browser.

And now…. the fun part begins!

To write a widget we need to follow three easy steps.

Develop your widget code

For this you can use the web development tool of your choice, but as an example we can start with something super simple, as follows (write it into a widget.htm document)

code01

Package your widget

Now we have our extremely functional widget code, now we need to create a manifest file (so the framework knows what to do with it) following the w3C widget standard for packaging and configuration (On 6.5 we support the December 22 2008 draft), but to make things easy, here is a small manifest, copy it into a config.xml file in the same folder as your widget.htm

code02

Don’t forget to also add an icon called icon.png on the same folder.

At this point, you should have three files (config.xml, icon.png and widget.htm), now we need to package them, on explorer, select the files, right click and send to a compressed folder (it is important to select the files and not the folder that contains them because we want config.xml to be in the root of the zip container). Now just rename the newly created zip file to “widget.wgt” and you are done with this step.

Deploy and run

On “Computer” you should see the cradled device emulator as “PocketPC device”

Use it to navigate to “My Documents” on the device and copy the widget file created in step 2 there. Now, on the emulator, open file explorer using the start menu and, listed there you should see your widget file, click on it.

This should start the installation process, once that is done you will see your very first widget on screen!!!

To continue playing with this widget (make it better, etc) you can find the uncompressed files on the “Program Files\Widgets\User\ folder” on the device.

The widget ID is generated at install time and it is an always increasing integer (therefore, the most recently installed widget will have the greatest number). You can replace, add, remove files here for testing at will; the only thing you need for a your widget to pick the changes up is to exit it and start it again, it will have an entry on the start menu.

I will be sharing more information about the widget API, how to extend the widget framework capabilities, debugging tips, best practices, etc in future posts but I wanted to help everyone to get started.

For now, you can also take a quick look at my TechDays session where I describe the API set and some of the capabilities of the framework. To access it you’ll need to log into the Microsoft Tech Days site and search for MBL302 Windows Mobile Web and Widgets: Leveraging web technologies to build experiences for Windows Mobile.

Stay tuned, have fun and don’t forget to share your thoughts… Also, before I forget, you can upload your cool widget creations to the Marketplace :), visit http://developer.windowsmobile.com for more information.

Jorge Peraza

SDK, DTK, DRK: WTF?!

10:56 am in Latest News, Software development, Windows Mobile by buzz_lightyear

This is one cool note, posted on Windows Mobile Team Blog @ microsoft!
Finally i know what WTF means :)

Earlier this week we released the Windows Mobile 6.5 Developer Toolkit (DTK). This release has raised a few questions relative to the other Windows Mobile software development tools and resources. I’d like to take a moment to describe what the SDK, DTK, and DRK are, and just as importantly what they are not.

Windows Mobile 6.5 Developer Resource Kit

SDK: Software Development Kit

We have not released a new SDK for Windows Mobile 6.5. The Windows Mobile 6 Professional SDK or Windows Mobile 6 Standard SDK are required for Windows Mobile 6.5 application development.

DTK: Developer Toolkit

The Windows Mobile 6.5 Developer Toolkit (DTK) is not an SDK! The DTK contains emulators, gesture APIs, and samples useful for developing Windows Mobile 6.5 applications. You will still need to install Microsoft Visual Studio® 2008 and the Windows Mobile 6 SDK prior to running the toolkit installer.

DRK: Developer Resource Kit

The Windows Mobile Developer Resource Kit (DRK) is an offline DVD copy of the most useful and relevant Windows Mobile application development tools and resources. Traditionally the DRK does not contain any exclusive content, in that nearly everything on the DRK is available for download online. This time we are pleased to publish the Windows Mobile 6.5 DRK with several sample chapters of Microsoft Mobile Development Handbook from Microsoft Press (Wigley, Moth, and Foot).

We hand out free copies of the DRK at several conferences and developer events throughout the year. Beginning in July 2009, you may also order the Windows Mobile 6.5 DRK online at this Microsoft Web site. The previously listed Windows Mobile 6 Developer Resource Kit will be replaced.

WTF: Where To Follow?

Follow us on Twitter @wmdev to get the inside scoop and up to date information for development on Windows Mobile!

Windows Mobile 6.5 DTK available for download

10:01 am in Latest News, Software development, Windows Mobile by buzz_lightyear

The Windows Mobile 6.5 Developer Tool Kit adds documentation, sample code, header and library files, emulator images and tools to Visual Studio that let you build applications for Windows Mobile 6.5. This document contains important information about this package. For general information about writing software for Windows Mobile, please see the Windows Mobile Developer Center. The Windows Mobile 6 SDK must also be installed in order to use any of the Windows Mobile 6.5 Gesture API or samples. Windows Mobile 6.5 Developer Tool Kit comes with the following.

Quick Details

Version: 6.5
Date Published: 6/3/2009
Language: English
Download Size: 71.4 MB – 1848.3 MB*
*Download size depends on selected download components.

Emulator Images

  • Windows Mobile 6.5 Professional Square Emulator
  • Windows Mobile 6.5 Professional QVGA Emulator
  • Windows Mobile 6.5 Professional WQVGA Emulator
  • Windows Mobile 6.5 Professional VGA Emulator
  • Windows Mobile 6.5 Professional WVGA Emulator
  • Windows Mobile 6.5 Standard Square Emulator
  • Windows Mobile 6.5 Standard QVGA Emulator

Available locales

  • 0804 CHS Chinese Simplified
  • 0409 USA English
  • 0407 GER German
  • 040c FRA French
  • 0410 ITA Italian
  • 0c0a ESN Spanish

A new set of APIs is being introduced that will enable application developers to take advantage of the new Windows Mobile 6.5 touch gesture framework. The gesture APIs allow an application to handle touch gesture input and provide a visually consistent experience with the rest of the device UI. Note that the gesture APIs are only available on the Windows Mobile Classic and Professional SKUs. The headers and libraries are installed in the Windows Mobile SDK\Pocket PC\ folder. Samples that make use of these APIs are installed into the Windows Mobile 6.5 Developer Tool Kit\Samples\ folder.System Requirements

Supported Operating Systems

  • Windows Server 2003 Service Pack 2
  • Windows Vista
  • Windows XP Service Pack 3

Download

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=20686a1d-97a8-4f80-bc6a-ae010e085a6e#filelist

Say good bye to GAPI

11:38 am in How To, Software development, Windows Mobile by buzz_lightyear

The Games API (GAPI) was a technology that allowed Windows Mobile 2003 applications to quickly draw graphics onto the device screen. It also contained functions that allowed an application to request all button press messages, even the ones that were normally intercepted by the Windows Mobile operating system.

The graphics component of GAPI was replaced by DirectDraw (which allowed hardware acceleration) in Windows Mobile 5.0. Application compatibility was maintained so that older programs would still work.

Most of the reference material for GAPI was removed from the Windows Mobile 6.1 documentation set, although the input functions were kept, so that applications could still request all key and button presses.  Application compatibility was maintained for this release as well.

This is all changing for the next generation of Windows Mobile, Windows Mobile 6.5.  Although some devices may still support GAPI, there is no longer a requirement for device manufacturers or mobile operators to ship or test for compatibility with GAPI.  This means that applications that require GAPI will provide an unpredictable experience for users on Windows Mobile 6.5 devices.

Another important change is that acceptance to the Windows Marketplace for Mobile and Designed for Windows Mobile certification requires no application dependencies on GAPI.

In order to replace the input functionality that GAPI once provided, a new keyboard API function is being made public.  This function is AllKeys(), and is defined below.  One great thing about this substitution is that AllKeys has been a part of Windows Mobile as long as GAPI, and is actually the API call that GAPI wrapped in order to publicly expose this functionality. This means that the transition to AllKeys should be easy, and backwards compatibility should be maintained.

You can migrate your input code to AllKeys in the following way:

Replace:

  • GXOpenInput() with AllKeys(TRUE).
  • GXCloseInput() with AllKeys(FALSE).

While AllKeys is set to true, all key presses will be sent to your application for handling.

Since GXOpenInput and GXCloseInput were simply wrappers for a call to AllKeys, so this substitution should cause no change in behavior in your programs.

The following is the definition of the new AllKeys API.

AllKeys

This function allows your programs to request that all key presses be sent directly to the requesting application. Normally some buttons are intercepted by the operating system for its own use, but games and input – intensive applications may want access to these buttons for their own use.

Syntax

BOOL AllKeys(
BOOL bAllKeys
);

Parameters

ParameterDescription
bAllKeys[in] If bAllKeys is set to TRUE, this function allows all keyboard events to be sent to the application. (This includes the soft-key buttons and back button).

If it is set to FALSE, this function specifies standard keyboard event behavior. Some events including soft-key buttons and the back button are not sent to the application.

Return Value

Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError.

Sample Code

The following C++ code illustrates how to use AllKeys. In the application that this sample is taken from, a check box is used to set AllKeys to true or false.

// process checkbox
case IDC_ALL_KEYS_CHECK_BOX:
if (g_AllKeys == true)
    {
    // Allow the OS to intercept some button presses
     AllKeys(FALSE);
    g_AllKeys = false;
    // set button state
    SendMessage(hwndCtl,BM_SETCHECK, BST_UNCHECKED,0);
    }
else
    {
    // Do not allow os to intercept button presses
    AllKeys(TRUE);
    g_AllKeys = true;
    //set button state
    SendMessage(hwndCtl,BM_SETCHECK, BST_CHECKED,0);
    }

Requirements

OS Versions: Windows Mobile 2003 and later.

Header: Winuser.h

How to start developing for Windows Mobile

9:33 am in How To, Software development, Windows Mobile by buzz_lightyear

Where to start?

It is safe to say that there are more options for development on Windows Mobile 6 than on any other mobile platform. WM has been around for a while, and Microsoft has built up a huge variety of APIs and development tools to support the platform. This is good – no matter what your preferred style of programming is, there is probably a supported solution on WM. It can also be confusing if you are trying to find out where to start when developing an application.

The options include:

  • Browser based development using scripting languages and Flash or Silverlight. This option is poorly supported in the existing mobile browsers, so at the moment, this is not a practical option.
  • Managed Code using . NET languages and the .NET Mobile Library.
  • Native coding using C++ and Windows Mobile native libraries.

Note: Not all Windows Mobile native libraries have managed equivalents. This means that the author of a managed program (in C# or VB for example) will have to use cumbersome and potentially unsafe methods to integrate the native library into the managed application if they wish to make use of the full libraries.

There are also different flavors of Windows Mobile 6: Standard and Professional. The big difference is that Professional devices have touch screens, and generally more features. It’s reasonable to expect that the performance of a professional device will be superior to that of a standard (no touch screen) device and the touch screen allows more input possibilities so I expect to focus on those devices.

At the moment, I’m not sure if I want to develop on managed or unmanaged code. I prefer to develop in C# using managed code, but may need the performance and APIs that are available to the C++ programmer. Luckily, I will use the same tools to develop both kinds of applications for WM, so I don’t have to decide what environment to use quite yet.

Reading up

In the past, the first stop in making sense of all these options would be to check Microsoft’s official documentation on MSDN, but that is changing. The official starting point for development on Windows Mobile is now the Windows Mobile Developer Portal.

For the moment, I actually prefer the material found on a different site -Windows Mobile Developer Center, although I’m told that these two sites will be integrated in the next few months. This site has webcasts, videos, and (of course) this blog.

The first thing I want to do is set up my development environment, and so I started looking for a section that would tell me how to start.  I already have a copy of Visual Studio 2008 installed, and wanted to use it, so I looked for that first.

Setting up

Note: Unlike the documentation on MSDN (Windows Mobile 6 Documentation) which only covers Visual Studio 2005, the information I found for setting up Visual Studio 2008 on the Developer Center was in videos. See http://code.msdn.microsoft.com/WM6YourFirstApp for a good getting started video.

Although the videos are current, excellent and accurate, watching the video is more time consuming than reading a procedure, (and impossible to find via search) so I’ll summarize them here:

  1. Install Visual Studio 2008. The SDK only works with the Standard and Professional editions, not with the free Express editions. There is a 90 day trial edition that you can download for free at the following web page: Try Visual Studio 2008 – Trial Software.
  2. Install the Visual Studio 2008 Service Pack 1 and .NET Framework 3.5 Service Pack 1. There may be other service packs available by the time you read this. Information on the latest service packs may be found at the following page: Visual Studio 2008 Development System.
  3. Download the Windows Mobile 6 SDKs from the following page: Mobile 6 Professional and Standard Software Development Kits Refresh. I am installing both, although I am planning on writing only for the Professional Edition device. You never know when you might change your mind!

Note: if you have installed the SDKs before Visual Studio 2008, you will need to remove and re-install them after the VS 2008 install.

Building a test application

To confirm that you have a working installation of Visual Studio and the SDK(s), try creating a simple application. I created a blank C++ project by following these steps:

  1. On the start page of Visual Studio 2008, in the upper left hand corner, there is a block titled “Recent Projects”. At the bottom of this block, there is a link for Opening a Project, and for Creating a Project. Choose Create Project.
  2. In the New Project dialog box, choose “Visual C++, then “Smart Device in the Project Types list. The Templates section should be populated with different project templates for different kinds of projects.
  3. Choose Win32 Smart Device Project, and enter a name for the project. “Test” is fine. Click OK.
  4. The Win32 Smart Device Project Wizard opens. The presets are set to Windows Mobile 5.0, which I don’t want to use, so I choose the Next button at the bottom of the dialog.
  5. This brings up a list of installed Windows Mobile SDKs. I am going to remove the Windows Mobile 5.0 SDK from the Selected SDKs list, and add the Windows Mobile6 Professional SDK and Windows Mobile Standard SDK. Once this is done, I click Next.
  6. In the Project Settings Dialog, I select “Windows application” and click Finish. The dialog closes, and Visual Studio creates a new project, populated with basic files, named “Test”.

In Visual Studio, I make sure that “Windows Mobile 6 Professional Emulator” is chosen in the drop down list on the upper left tool bar. I then build the application “Test”, and choose to start debugging.

The Emulator appears, and in a moment, my application (with a blank screen) loads and is displayed in the emulator.

emulator

Clicking on the close icon in the upper right hand corner shuts down my application, and Visual Studio returns to its default state.

Excellent – that was easy, and everything works!

If I wanted to build for a different flavor of Windows Mobile (Standard, Windows Mobile 5, or deploy to an actual device, I would choose a different option from the upper left hand tool bar drop down. Does it all make sense so far?

Windows Mobile Marketplace registration open

8:11 am in Software development, Windows Mobile by buzz_lightyear

Marketplace Registration Open!

In the latest update to http://developer.windowsmobile.com, developers can now Register to participate in Windows Marketplace for Mobile. This marks another milestone in providing Windows Mobile Developers a clear path to develop, test, certify and distribute their Windows Mobile applications via the Windows® Marketplace for Mobile. Throughout the registration process, links to key documentation for distributing apps through Windows Marketplace for Mobile are provided.

Next steps for developers?

Finally, if you have any questions for the team that are not already addressed in the Windows Marketplace for Mobile FAQ, I invite you to write a comment below.

marketplace

The Best of Source Code Comments

2:03 pm in Software development by buzz_lightyear

Well.. do you write comments in your source code? I’m sure you do, but are they funny enough?

Then join the Best Comments in Source Code at Stack Overflow site or at least read it. Your satisfaction is guaranteed :)

Some examples:

/**
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}
stop(); // Hammertime!
// sometimes I believe compiler ignores all my comments
// I dedicate all this code, all my work, to my wife, Darlene, who will
// have to support me and our three children and the dog once it gets
// released into the public.
// drunk, fix later
// Magic. Do not touch.
//When I wrote this, only God and I understood what I was doing
//Now, God only knows
//
// Dear maintainer:
//
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
//
// total_hours_wasted_here = 16
//

grab_it ROM dumper [source code]

10:03 am in Software development, Windows Mobile by buzz_lightyear

Here’s the source code of grab_it tool.
I wrote it sometimes around may/june 2005 for some specific reason.

Maybe someone find this c++ source code useful.

// grab_it.cpp : Defines the entry point for the application.
// by buzz_lightyear
// sometime around may/june 2005
// http://buzzdev.net

#include "stdafx.h"
#include "windows.h"

// in this case, dump will be saved to MiniSD card
#define targetFile L"\Mini-SD\dump.bin"

int		lineHeight=1;		//progress bar height
int		drawPoint=319;
int		BarPosition=0;
int		screenWidth = GetSystemMetrics(SM_CXSCREEN);
HDC		hdc = ::GetDC(NULL);
HPEN	lineProgress,lineBackground,po;	// Pen Progress bar

wchar_t	Buff[1024];		// buffer for Error messages

DWORD	DumpStart=0x00000000;		//start address
DWORD	DumpSize=0x8000000;			//Size
DWORD	Step=0x80000;

extern "C" BOOL VirtualCopy(
  LPVOID lpvDest,
  LPVOID lpvSrc,
  DWORD cbSize,
  DWORD fdwProtect
);

int ShowProgress(int pos){
	MoveToEx(hdc,0,drawPoint,NULL);

	po = (HPEN)SelectObject(hdc,lineBackground);
	LineTo(hdc,pos,drawPoint);

    SelectObject(hdc,lineProgress);
    LineTo(hdc,screenWidth,drawPoint);

	SelectObject(hdc,lineBackground);
    LineTo(hdc,screenWidth,drawPoint);

return 0;
}

int ShowError(wchar_t text[1024]){
	MessageBox(NULL,text,L"ERROR",MB_OK | MB_TOPMOST | MB_SETFOREGROUND);
	return 0;
}

int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPTSTR    lpCmdLine,
					int       nCmdShow)
{/// 1st

	lineProgress = CreatePen(PS_SOLID,lineHeight,RGB(255,0,0)); // Progress bar
	lineBackground = CreatePen(PS_SOLID,lineHeight,RGB(100,100,100)); // Background bar

	HANDLE H=CreateFile(targetFile,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_FLAG_WRITE_THROUGH,0);
	if(H==INVALID_HANDLE_VALUE)
	{
		MessageBox(NULL,L"Cannot create file!",L"Error",MB_OK);
		return 1;
	}

	//for( i; i<(DumpStart+DumpSize); i+=Step)
	{
		LPVOID Ptr=VirtualAlloc(
			0,
			512*1024,
			MEM_RESERVE,
			PAGE_READONLY
			);
		if(Ptr==0)
		{
			wsprintf(Buff,L"Cannot allocate %08X",i);
			ShowError(Buff);
			return 1;
		}
		/// update progress bar ///
		BarPosition=((i-DumpStart)/(DumpSize/screenWidth));
		ShowProgress(BarPosition);
		///////////////////////////

		if(!VirtualCopy(Ptr,(void*)(i/256),512*1024,PAGE_EXECUTE_READWRITE|PAGE_PHYSICAL))
		{
			wsprintf(Buff,L"Cannot map %08X",i);
			ShowError(Buff);
			return 1;
		}
		DWORD W=0;
		WriteFile(H,Ptr,512*1024,&W,0);
		if(W!=512*1024)
		{
			wsprintf(Buff,L"Error on WriteFile. Card full?",i);
			ShowError(Buff);
			return 1;
		}
		VirtualFree(Ptr,0,MEM_RELEASE);
	}

	CloseHandle(H);

	MessageBeep(MB_OK);

	DeleteObject(lineBackground);
	DeleteObject(lineProgress);
	return 0;
}

Extended ROM unlocker for WindowsMobile 2005

10:53 am in Software development by buzz_lightyear

Here’s the source code of Extended ROM unlocker for:

  • HTC Himalaya
  • HTC Prophet
  • HTC Apache
  • HTC Universal

This c++ source works on WindowsMobile 2005 operating system (see the comment in source).

DiskOnChip (DOC) is protected by simple plaintext password, which is readable in bootloader/SPL dumps.

The code is pretty simple and easy, however, if you don’t understand something, feel free to post a comment and ask.

// **********************************************************
// HTC Prophet/Himalaya/Apache/Universal ExtendedROM unlocker
// for WindowsMobile 2005
// by buzz_lightyear
// http://buzzdev.net
// May 2006
// **********************************************************

#include
#include
#include "diskio.h"
#include
#include "ceioctl.h"

#define BUFFER_SIZE 0x200

// this handle works on WindowsMobile2005
LPCTSTR diskname = L"\Extended_ROM\Vol:";

DWORD nReturned = 0;
HANDLE hDevice = NULL;
flProtectionOutput out;

FLStatus PrintFLStatus(const FLStatus bStat) ;

bool PartitionInsertKey(HANDLE hDsk, bool bInsert)
  {
	  BYTE in[10];

  in[0]= 0;
        //      COMMENT/UNCOMMENT as apropriate for given device
        //      |--------------------- HTC Prophet DOC password
        //      |     |--------------- HTC Himalaya DOC password
        //      |     |     |--------- HTC Apache DOC password
        //      |     |     |     |--- HTC Universal DOC password
	in[1]= 'a';//'a';//'A';// a
	in[2]= '!';//'Y';//'p';// S
	in[3]= '0';//'a';//'a';// r
	in[4]= '3';//'L';//'c';// E
	in[5]= '2';//'a';//'M';// v
	in[6]= '1';//'M';//'V';// I
	in[7]= '9';//'i';//'9';// n
	in[8]= '1';//'H';//'4';// U
	in[9]= bInsert?PROTECTION_INSERT_KEY:PROTECTION_REMOVE_KEY;

	memset(&out, 0, sizeof(out));

    DWORD nReturned=0;
    if (!DeviceIoControl(hDsk, FL_IOCTL_BDTL_HW_PROTECTION, &in, sizeof(in), &out, sizeof(out), &nReturned, NULL)) {
		PrintFLStatus(out.status);
        return false;
    }
	//PrintFLStatus(out.status);
    return true;
}

bool PartitionChangeType(HANDLE hDsk, DWORD dwType)
{
    BYTE in[10];

    in[0]= (BYTE)dwType;
	in[1]= 'a';//'a';//'A';// a
	in[2]= '!';//'Y';//'p';// S
	in[3]= '0';//'a';//'a';// r
	in[4]= '3';//'L';//'c';// E
	in[5]= '2';//'a';//'M';// v
	in[6]= '1';//'M';//'V';// I
	in[7]= '9';//'i';//'9';// n
	in[8]= '1';//'H';//'4';// U
    in[9]= PROTECTION_CHANGE_TYPE;

    memset(&out, 0, sizeof(out));

    DWORD nReturned=0;
    if (!DeviceIoControl(hDsk, FL_IOCTL_BDTL_HW_PROTECTION, &in, sizeof(in), &out, sizeof(out), &nReturned, NULL)) {
        //error("FL_IOCTL_BDTL_HW_PROTECTION");
		PrintFLStatus(out.status);
        return false;
    }
	PrintFLStatus(out.status);
    return true;
}

bool unlockdisk(HANDLE hDsk)
{
    if (PartitionInsertKey(hDsk, true) &&  PartitionChangeType(hDsk, PROTECTABLE))
	{
	return true;
	}
	return false;
}

//TRACE
void TRACE(LPCTSTR szFormat, ...)
{

	TCHAR szBuffer[BUFFER_SIZE];

	va_list pArgs;
	va_start(pArgs, szFormat);
	wvsprintf(szBuffer, szFormat, pArgs);
	va_end(pArgs);

	_tcscat(szBuffer, TEXT("rn"));
	OutputDebugString(szBuffer);
}

FLStatus PrintFLStatus(const FLStatus bStat)
{
	switch(bStat)
	{
	case flOK: TRACE(TEXT("FLStatus: OKn"));
		MessageBox(NULL, L"SUCCESS", L"OK", MB_OK | MB_ICONWARNING | MB_TOPMOST | MB_SETFOREGROUND | MB_APPLMODAL);
		break;
	case flBadFunction:
		TRACE(TEXT("FLStatus: BadFunctionn")) ;
		break ;
	case flFileNotFound:
		TRACE(TEXT("FLStatus: FileNotFoundn")) ;
		break ;
	case flPathNotFound:
		TRACE(TEXT("FLStatus: PathNotFoundn")) ;
		break ;
	case flTooManyOpenFiles:
		TRACE(TEXT("FLStatus: TooManyOpenFilesn")) ;
		break ;
	case flNoWriteAccess:
		TRACE(TEXT("FLStatus: NoWriteAccessn")) ;
		break ;
	case flBadFileHandle:
		TRACE(TEXT("FLStatus: BadFileHandlen")) ;
		break ;
	case flDriveNotAvailable:
		TRACE(TEXT("FLStatus: DriveNotAvailablen")) ;
		break ;
	case flNonFATformat:
		TRACE(TEXT("FLStatus: NonFATformatn")) ;
		break ;
	case flFormatNotSupported:
		TRACE(TEXT("FLStatus: FormatNotSupportedn")) ;
		break ;
	case flNoMoreFiles:
		TRACE(TEXT("FLStatus: NoMoreFilesn")) ;
		break ;
	case flWriteProtect:
		TRACE(TEXT("FLStatus: WriteProtectn")) ;
		break ;
	case flBadDriveHandle:
		TRACE(TEXT("FLStatus: BadDriveHandlen")) ;
		MessageBox(NULL, L"BadDriveHandle", L"Error", MB_OK | MB_ICONWARNING | MB_TOPMOST | MB_SETFOREGROUND | MB_APPLMODAL);
		break ;
	case flDriveNotReady:
		TRACE(TEXT("FLStatus: DriveNotReadyn")) ;
		MessageBox(NULL, L"DriveNotReady", L"Error", MB_OK | MB_ICONWARNING | MB_TOPMOST | MB_SETFOREGROUND | MB_APPLMODAL);
		break ;
	case flUnknownCmd:
		TRACE(TEXT("FLStatus: UnknownCmdn")) ;
		break ;
	case flBadFormat:
		TRACE(TEXT("FLStatus: BadFormatn")) ;
		break ;
	case flBadLength:
		TRACE(TEXT("FLStatus: BadLengthn")) ;
		break ;
	case flDataError:
		TRACE(TEXT("FLStatus: DataErrorn")) ;
		break ;
	case flUnknownMedia:
		TRACE(TEXT("FLStatus: UnknownMedian")) ;
		break ;
	case flSectorNotFound:
		TRACE(TEXT("FLStatus: SectorNotFoundn")) ;
		break ;
	case flOutOfPaper:
		TRACE(TEXT("FLStatus: OutOfPapern")) ;
		break ;
	case flWriteFault:
		TRACE(TEXT("FLStatus: WriteFaultn")) ;
		break ;
	case flReadFault:
		TRACE(TEXT("FLStatus: ReadFaultn")) ;
		break ;
	case flGeneralFailure:
		TRACE(TEXT("FLStatus: GeneralFailuren")) ;
		break ;
	case flDiskChange:
		TRACE(TEXT("FLStatus: DiskChangen")) ;
		break ;
	case flVppFailure:
		TRACE(TEXT("FLStatus: VppFailuren")) ;
		break ;
	case flBadParameter:
		TRACE(TEXT("FLStatus: BadParametern")) ;
		break ;
	case flNoSpaceInVolume:
		TRACE(TEXT("FLStatus: NoSpaceInVolumen")) ;
		break ;
	case flInvalidFATchain:
		TRACE(TEXT("FLStatus: InvalidFATchainn")) ;
		break ;
	case flRootDirectoryFull:
		TRACE(TEXT("FLStatus: RootDirectoryFulln")) ;
		break ;
	case flNotMounted:
		TRACE(TEXT("FLStatus: NotMountedn")) ;
		break ;
	case flPathIsRootDirectory:
		TRACE(TEXT("FLStatus: PathIsRootDirectoryn")) ;
		break ;
	case flNotADirectory:
		TRACE(TEXT("FLStatus: NotADirectoryn")) ;
		break ;
	case flDirectoryNotEmpty:
		TRACE(TEXT("FLStatus: DirectoryNotEmptyn")) ;
		break ;
	case flFileIsADirectory:
		TRACE(TEXT("FLStatus: FileIsADirectoryn")) ;
		break ;
	case flAdapterNotFound:
		TRACE(TEXT("FLStatus: AdapterNotFoundn")) ;
		break ;
	case flFormattingError:
		TRACE(TEXT("FLStatus: FormattingErrorn")) ;
		break ;
	case flNotEnoughMemory:
		TRACE(TEXT("FLStatus: NotEnoughMemoryn")) ;
		break ;
	case flVolumeTooSmall:
		TRACE(TEXT("FLStatus: VolumeTooSmalln")) ;
		break ;
	case flBufferingError:
		TRACE(TEXT("FLStatus: BufferingErrorn")) ;
		break ;
	case flFileAlreadyExists:
		TRACE(TEXT("FLStatus: FileAlreadyExistsn")) ;
		break ;
	case flIncomplete:
		TRACE(TEXT("FLStatus: Incompleten")) ;
		break ;
	case flTimedOut:
		TRACE(TEXT("FLStatus: TimedOutn")) ;
		break ;
	case flTooManyComponents:
		TRACE(TEXT("FLStatus: TooManyComponentsn")) ;
		break ;
	case flTooManyDrives:
		TRACE(TEXT("FLStatus: TooManyDrivesn")) ;
		break ;
	case flTooManyBinaryPartitions:
		TRACE(TEXT("FLStatus: TooManyBinaryPartitionsn")) ;
		break ;
	case flPartitionNotFound:
		TRACE(TEXT("FLStatus: PartitionNotFoundn")) ;
		break ;
	case flFeatureNotSupported:
		TRACE(TEXT("FLStatus: FeatureNotSupportedn")) ;
		break ;
	case flWrongVersion:
		TRACE(TEXT("FLStatus: WrongVersionn")) ;
		break ;
	case flTooManyBadBlocks:
		TRACE(TEXT("FLStatus: TooManyBadBlocksn")) ;
		break ;
	case flNotProtected:
		TRACE(TEXT("FLStatus: NotProtectedn")) ;
		MessageBox(NULL, L"ExtROM is not protectednwith password.", L"Error", MB_OK | MB_ICONWARNING | MB_TOPMOST | MB_SETFOREGROUND | MB_APPLMODAL);
		break ;
	case flBadBBT:
		TRACE(TEXT("FLStatus: BadBBTn")) ;
		break ;
	case flWrongKey:
		TRACE(TEXT("FLStatus: WrongKeyn"));
		MessageBox(NULL, L"WrongKey", L"Error", MB_OK | MB_ICONWARNING | MB_TOPMOST | MB_SETFOREGROUND | MB_APPLMODAL);
		break ;
	case flHWProtection:
		TRACE(TEXT("FLStatus: HWProtectionn")) ;
		MessageBox(NULL, L"HWProtection", L"Error", MB_OK | MB_ICONWARNING | MB_TOPMOST | MB_SETFOREGROUND | MB_APPLMODAL);
		break ;
	case flBadDownload:
		TRACE(TEXT("FLStatus: BadDownloadn")) ;
		break ;
	default:
		TRACE(TEXT("FLStatus: Unknown statusn")) ;
		MessageBox(NULL, L"Unknown status", L"Error", MB_OK | MB_ICONWARNING | MB_TOPMOST | MB_SETFOREGROUND | MB_APPLMODAL);
		break ;
}

return (bStat) ;
}

///////////////////////////////////
///////////////////////////////////
///////////////////////////////////
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hInstPrev, LPWSTR pszCmdLine, int nCmdShow)
{
	hDevice = CreateFile(diskname, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (hDevice == NULL || hDevice == INVALID_HANDLE_VALUE)
	{
		TRACE(TEXT("Create handle failed."));
		return 1;
	}
	TRACE(TEXT("Create handle succeededn"));

	if (unlockdisk(hDevice))
	{
		TRACE(L"Unlockedn");
	}

	//	default:
	if(hDevice)
	{
		CloseHandle(hDevice);
		hDevice = NULL;
	}

	return 0;
}
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////