Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ZXing.Net.Mobile sample for Windows Phone Silverlight
using ZXing.Mobile;
public partial class MainPage : PhoneApplicationPage
{
private readonly MobileBarcodeScanner scanner;
public MainPage()
{
InitializeComponent();
scanner = new MobileBarcodeScanner(Dispatcher);
//ハードウェアの戻るボタン時にスキャンを中断する
HardwareButtons.BackPressed += (sender, args) =>
{
scanner.Cancel();
};
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
scanner.Cancel();
base.OnNavigatedFrom(e);
}
private void Start()
{
// デフォルトのOverlayは使わない
scanner.UseCustomOverlay = false;
// スキャン実行時に画面に表示するテキスト
scanner.TopText = $"イベントに登録します";
scanner.CancelButtonText = "キャンセル";
//スキャンを連続的に実行。
//スキャンされるごとに結果がresultに渡されてラムダ式が実行される。
scanner.ScanContinuously(result =>
{
scanner.BottomText = "";
if (string.IsNullOrEmpty(result?.Text))
{
return;
}
// UI要素を更新するのでUIスレッドで。
Dispatcher.BeginInvoke(async () =>
{
var client = new HttpClient();
//DoorkeeperはUAで端末を判別するっぽい
client.DefaultRequestHeaders.UserAgent.ParseAdd("DoorKeeper Registration for Windows Phone");
//スキャンした結果のURLを使ってHTTP通信
var res = await client.GetAsync(new Uri(result.Text));
if (!res.IsSuccessStatusCode)
{
scanner.BottomText = "チェックイン失敗";
return;
}
//HTTP通信した結果、普通のWebページが返ってくるのでパースしてユーザー名を取得する
var r = await res.Content.ReadAsStringAsync();
var l = r.Split('\r', '\n').FirstOrDefault(line => line.StartsWith("<p class='indented'>"));
var user = l?.Substring("<p class='indented'>".Length, l.Length - "<p class='indented'>".Length - "</p>".Length);
if (user == null)
return;
MessageBox.Show($"{user} さん、チェックイン完了");
});
});
}
public void SaveTextToLocalSetting(string key, string value)
{
var container = ApplicationData.Current.LocalSettings;
container.Values[key] = value;
}
public string LoadTextFromLocalSetting(string key)
{
var container = ApplicationData.Current.LocalSettings;
if (container.Values.ContainsKey(key))
{
return container.Values[key] as string;
}
else
{
return null;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.