Click here to Skip to main content
15,885,244 members
Articles / Programming Languages / C++
Tip/Trick

Fetching the name of your Windows Phone 8

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
11 Nov 2013CPOL 9.1K   3  
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:

C++
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:

C++
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h> 

Replace NetFred.h with this simple ref class containing a single static property:

C++
#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:

C++
#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:

C++
var name = NetFred.DeviceName.PhoneName; 

Great, we are finished!

Any comments are welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Tunisia Tunisia
Microsoft Certified Professional, Big Data and Cloud Architect.
Mail : hadrichmed@gmail.com

Comments and Discussions

 
-- There are no messages in this forum --