Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Fetching the name of your Windows Phone 8

0.00/5 (No votes)
11 Nov 2013 1  
This article shows you how to fetch the name of your Windows Phone 8 using some C++/CX code.

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here