Introduction
If you are familiar with C++/CX code and you want to build a Windows Phone 8 application that
names or gets the name of your Windows Phone 8 device, you are at the right place.
Using the code
Windows Phone 8 provides developers with a rich API that allows them to name their phone whatever they like and they can display the name of their application.
So, here is some C++/CX code to show exactly:
Platform::String ^ DeviceName::PhoneName::get()
{
WSADATA wsadata;
ADDRINFOA *result = nullptr;
int error;
wchar_t wszName[256] = L"Unknown";
ADDRINFOA hints = {};
hints.ai_flags = AI_CANONNAME;
error = WSAStartup(MAKEWORD(2,2), &wsadata);
if (error==0)
{
error = ::getaddrinfo("", "0", &hints, &result);
if (error==0)
{
char *name = result->ai_canonname;
if (name!=nullptr)
{
MultiByteToWideChar(CP_ACP, 0, name, strlen(name), wszName, 256);
}
}
}
::freeaddrinfo(result);
return ref new Platform::String(wszName);
}
If you have no experience with C++/CX on the phone don't worry, you can follow these simple steps.
Load your C# project into Visual Studio 2012. Right click on the Solution then
add then New Project, then Visual C++, then Windows Phone, then Windows Phone Runtime
Component, and call it NetFred.
In pch.h, add:
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
Replace NetFred.h with this simple ref class containing a single static property:
#pragma once
namespace NetFred
{
public ref class DeviceName sealed
{
public:
static property Platform::String ^ PhoneName
{
Platform::String ^ get();
}
};
}
Replace NetFred.cpp with the code at the start of the article, prefixed with this:
#include "pch.h"
#include "NetFred.h"
using namespace NetHelper;
using namespace Platform;
#pragma comment(lib, "ws2_32.lib")
Build the NetFred project.
Right click on your C# project's References tree, then Add Reference, then Solution, then add a checkmark next to NetFred, then OK.
In C#, you can now use it:
var name = NetFred.DeviceName.PhoneName;
Great, we are finished!
Any comments are welcome.