WinJS App with Windows Runtime Component to Access Native C# Methods

In this article, we will learn how to connect WinJS project with Windows Runtime Component to access native C# methods.
Let’s get started.
Step 1:
First, create a WinJS project as discussed in this blog: Create Your First WinJS Windows Application
Step 2:
Now we will add a Windows Runtime Component. For this, go to File > Add > New Project.
Step 3:
Under Other Languages > Visual C# > Windows, Select Windows Runtime Component (Windows 8.1). Name it as WinRuntimes and Click OK.
Step 4:
Delete the default class ‘Class1’ and add a new class Service by Right Click on the WinRuntimes project and add the new class.
Step 5:
Name this class as Service and click Add.
In Service Class, make Service as sealed class and add function Hello() which returns string “Hello World”.
Complete code snippet is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinRuntimes
{
public sealed class Service
{
public string Hello()
{
return "Hello World";
}
}
}
Step 6:
Now we have to add this WinRuntimes as the reference in our WinJS project. Right, Click on References > Add Reference.
Step 7:
Under Projects > Solution > Select WinRuntimes and Click OK.
(You will see a reference added in our WinJS project. Build this project or press Ctrl + Shift + B.)
Step 8:
Add a script.js file and reference it in HTML similar as discussed in the previous blog: Create Your First WinJS Windows Application.
Let’s add following things in HTML.
- Button with click event.
- Input field.
Our complete HTML looks like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hello_WinJS</title>
<link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.2.0/js/base.js"></script>
<script src="//Microsoft.WinJS.2.0/js/ui.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<p>Hello WinJS</p>
<button onclick="getString()">Click Me</button>
<input id="txtInput"/>
</body>
</html>
Step 9:
In script.js, we will add getString() function with a service object that calls the method Hello() of WinRuntimes (Windows Runtime Component) like:
function getString() {
var service = new WinRuntimes.Service();
var message = service.hello();
document.getElementById("txtInput").value = message;
}
Step 10:
Now we are ready to run our application, Press F5 and click on Click Me button. You will see “Hello World” in the input field that is retrieved from out native C# methods using Windows Runtime Component. In the next blog, I will show you how to do asynchronous operations in Runtime Components.
That’s it.
Thanks! Happy Coding.
Discussion