首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows 7 感應器開發實戰(一):建立 WPF 應用程式與感應器助手架構

     編輯:關於.NET

Windows 7 感應器與位置平台優勢

  • 硬體獨立:統一 API 操作所有感應器類型,無需學習廠商專有 API
  • 隱私保護:預設關閉,使用者透過控制台啟用,應用程式需請求權限
  • 應用程式共享:多應用程式可同時存取同一感應器資料
  • 位置簡化:Location API 自動選擇最佳定位來源(GPS、Wi-Fi、基地台),無需實作 NMEA 協定

可調式 MSDN 閱讀器

圖 1:使用環境光感應器調整對比度、尺寸與色彩飽和度的 MSDN 閱讀器

系統需求

  • Visual Studio 2008 SP1
  • Windows 7 RC 或更新版本
  • 支援 DirectX 與 Pixel Shader 的顯示卡
  • 已安裝驅動的 Windows 7 相容環境光感應器硬體或虛擬感應器
  • 3D 加速度計硬體(可選)

練習:WPF 應用程式整合感應器 API

任務 1:準備 WPF 專案

  1. 開啟 Starter 資料夾中的初始解決方案 SensorHOL
  2. 專案已內建 Grayscale PixelShader 效果與 WPF 控制項資源
  3. 新增 SensorViewModel 類別,實作 INotifyPropertyChanged:
class SensorViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyChange(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
  1. MainWindow.xaml.cs 建構函式設定 DataContext:
public MainWindow()
{
    InitializeComponent();
    DataContext = new SensorViewModel();
}

任務 2:設計 MainWindow 版面配置

三區域設計:

  • 頂部:Browse 按鈕與照片名稱
  • 左側:感應器指示器
  • 右側:疊加顯示的兩張圖片,滑桿控制遮罩分隔

Grid 列/欄定義

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="65"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="150"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    ...
</Grid>

右側疊加內容區

<Grid x:Name="OverlayContent" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">
    <Image Stretch="Uniform" Margin="10"/>
    <Image Stretch="Uniform" Margin="10"/>
    <Slider x:Name="OverlayAdjustmentSlider"
        Width="{Binding ElementName=OverlayContent, Path=ActualWidth}"
        Height="{Binding ElementName=OverlayContent, Path=ActualHeight}"
        Maximum="1" Minimum="0" Value="0.5"
        Template="{DynamicResource Slider_ControlTemplate}"/>
</Grid>

左側感應器資料區

<Grid Width="150" Height="240" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top">
    <Border Background="{DynamicResource Brush_PopupBackground}" ...>
        <Border.Effect>
            <DropShadowEffect BlurRadius="12" Direction="-90" ShadowDepth="3"/>
        </Border.Effect>
    </Border>
    <Border Background="{DynamicResource Brush_PopupBackground}" BorderBrush="{StaticResource Brush_PopupBorder}" BorderThickness="0,1,0,1" CornerRadius="3">
        <Grid TextElement.FontFamily="Segoe UI" TextElement.FontSize="10">
            <TextBlock HorizontalAlignment="Center" Margin="0,10" VerticalAlignment="Top" FontSize="13" Foreground="White" Text="Sensor Data"/>
        </Grid>
    </Border>
</Grid>

頂部工具列

<Grid Grid.ColumnSpan="2" HorizontalAlignment="Stretch">
    <Button HorizontalAlignment="Left" Width="70" Margin="5" Height="40" Content="Browse..." Click="Button_Click"/>
    <TextBlock Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Segoe UI" Text="{Binding ImageName, Mode=OneWay}"/>
</Grid>

任務 3:實作圖片選取邏輯

  1. SensorViewModel 加入 ImagePath 與 ImageName 屬性:
private string _imagePath;
public string ImagePath
{
    get { return _imagePath; }
    set {
        _imagePath = value;
        NotifyChange("ImagePath");
        NotifyChange("ImageName");
    }
}
public string ImageName
{
    get { return System.IO.Path.GetFileNameWithoutExtension(ImagePath); }
}
  1. XAML 繫結圖片來源與名稱:
<Image Source="{Binding ImagePath}" Stretch="Uniform" Margin="10"/>
<TextBlock Text="{Binding ImageName, Mode=OneWay}" .../>
  1. MainWindow.xaml.cs 實作按鈕點擊開啟檔案對話框:
private void Button_Click(object sender, RoutedEventArgs e)
{
    var dlg = new Microsoft.Win32.OpenFileDialog {
        Filter = "Image Files|*.jpg;*.png",
        Title = "Find an Image"
    };
    if (dlg.ShowDialog() == true)
        (DataContext as SensorViewModel).ImagePath = dlg.FileName;
}

任務 4:建立感應器助手類別

  1. 加入 Microsoft.WindowsAPICodePack.Sensors.dll 參考
  2. 建立泛型 SensorHelper<SensorType, SensorPropertyType>:
public class SensorHelper<SensorType, SensorPropertyType> : INotifyPropertyChanged
    where SensorType : Sensor
    where SensorPropertyType : class
{
    private SensorPropertyType _value;
    private SensorType _sensor;
    private Guid _sensorGUID;

    public void Initialize()
    {
        var list = SensorManager.GetSensorsByTypeId<SensorType>();
        if (list != null)
        {
            var permList = new SensorList<Sensor>();
            foreach (var s in list) permList.Add(s);
            SensorManager.RequestPermission(IntPtr.Zero, true, permList);

            foreach (var s in list)
                if (HandleNewSensor(s) && _sensor != null) break;
        }
        SensorManager.SensorsChanged += OnSensorsChanged;
    }
    ...
}

核心事件處理

  • OnSensorsChanged:處理感應器新增/移除,新增時檢查類型並呼叫 HandleNewSensor
  • HandleNewSensor:訂閱 StateChanged,若狀態為 Ready 呼叫 PrepareSensor
  • OnSensorStateChanged:狀態變為 Ready 時準備感應器,非 Ready 時清理
  • PrepareSensor:設定使用中感應器、呼叫 TryUpdateData() 取得初始資料、訂閱 DataReportChanged
  • OnDataUpdated:依感應器型別擷取 CurrentLuminousIntensity 或 CurrentAcceleration,觸發 PropertyChanged("Value")

屬性公開與通知

public SensorPropertyType Value { get { return _value; } }

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
    var ph = PropertyChanged;
    if (ph != null) ph(this, new PropertyChangedEventArgs(name));
}

此架構封裝感應器發現、權限請求、狀態管理與資料更新,為 UI 資料繫結提供穩定基礎。下一階段將整合至 ViewModel 並建構互動介面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved