Let's get started.

Step 1:

Firstly, create a WinJS project as discussed in in my following article. For that we will start with creating a blank Universal Windows App:

Create you first WinJS Application

Step 2:

Now we will add a Windows Runtime Component. For this, go to File, Add, then click New Project.


Step 3:

Under Other Languages, Visual C#, then Windows, elect Windows Runtime Component (Windows 8.1). Name it WinRuntimes and click OK.

Step 4:

Delete the default class ‘Class1’ and add a new class Service by right click ing the WinRuntimes project and add 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:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace WinRuntimes
  7. {
  8. public sealed class Service
  9. {
  10. public string Hello()
  11. {
  12. return "Hello World";
  13. }
  14. }
  15. }
Step 6:

Now we have to add this WinRuntimes as reference in our WinJS project. Right Click on References > Add Reference.



Step 7:

Under Projects, Solution, then 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 similarly discussed in previous article.

Let us add the following things in HTML.

  • Button with click event.
  • Input field

Our complete HTML looks like:
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>Hello_WinJS</title>
  6. <!-- WinJS references -->
  7. <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />
  8. <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
  9. <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>
  10. <!-- Hello_WinJS references -->
  11. <link href="/css/default.css" rel="stylesheet" />
  12. <script src="/js/default.js"></script>
  13. <script src="js/script.js"></script>
  14. </head>
  15. <body>
  16. <p>Hello WinJS</p>
  17. <button onclick="getString()">Click Me</button>
  18. <input id="txtInput"/>
  19. </body>
  20. </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:

  1. function getString() {
  2. var service = new WinRuntimes.Service();
  3. var message = service.hello();
  4. document.getElementById("txtInput").value = message;
  5. }

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 native C# code using Windows Runtime Component.

In the coming articles, I will show you how to do asynchronous operations in Runtime Components.
That’s it.

Thanks! Happy Coding.

Read more articles on Universal Windows Apps: