Windows運作時元件是Windows 8裡面通用的公共庫,它可以使用C++,C#或者VB來編寫,不過你的Windows 8 metro是用什麼語言編寫都可以調用無縫地調用Windows運作時元件。
下面通過一個C#編寫的Windows 8項目來調用一個用C++編寫的Windows運作時元件。
建立一個Windows運作時元件:
編寫如下的代碼:
#include "pch.h"
#include "WinRTComponent.h"
using namespace CppWinRTComponentDll2;
int CalculatorSample::Add(int x, int y)
{
return x+y;
}
頭檔案
#pragma once
using namespace Windows::Foundation;
namespace CppWinRTComponentDll2
public ref class CalculatorSample sealed
{
public:
int Add(int x, int y);
};
在C#編寫的項目中調用Windows運作時元件的C++方法
添加Windows運作時元件
UI部分
<Page
x:Class="TestWinRTCSDemo.MainPage"
IsTabStop="false"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestWinRTCSDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<TextBox x:Name="txtX" HorizontalAlignment="Center" Height="45" Width="258"></TextBox>
<TextBlock Text="+" HorizontalAlignment="Center" Height="45" Width="258" FontSize="14" FontWeight="Bold"/>
<TextBox x:Name="txtY" HorizontalAlignment="Center" Height="45" Width="258"></TextBox>
<Button Content="調用WinRT方法來相加" HorizontalAlignment="Center" Click="Button_Click_1" ></Button>
<TextBox x:Name="txtAddResult" HorizontalAlignment="Center" Height="45" Width="258"/>
</StackPanel>
</Grid>
</Page>
C#代碼部分
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using CppWinRTComponentDll2;//引入Windows運作時的空間
namespace TestWinRTCSDemo
public sealed partial class MainPage : Page
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
private void Button_Click_1(object sender, RoutedEventArgs e)
if (txtX.Text != "" && txtY.Text != "")
{
CalculatorSample calcobj = new CalculatorSample();//直接建立Windows運作時裡面的對象,很友善
int x = Convert.ToInt32(txtX.Text.ToString());
int y = Convert.ToInt32(txtY.Text.ToString());
txtAddResult.Text = calcobj.Add(x,y).ToString();//調用Windows運作時裡面的方法
}
}
運作的效果
本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1081671