master
wanggang 4 years ago
parent d32f072457
commit 436d8a5d7c

@ -35,7 +35,7 @@ namespace PhotoCollector
var userDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Application.ProductName);
var env = await CoreWebView2Environment.CreateAsync(browserExecutableFolder, userDataFolder);
this.webView21.NavigationCompleted += WebView21_NavigationCompleted;
this.webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompleted;
this.webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompletedAsync;
await this.webView21.EnsureCoreWebView2Async(env);
}
@ -47,7 +47,7 @@ namespace PhotoCollector
}
}
private void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
private async void WebView21_CoreWebView2InitializationCompletedAsync(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
var webView = sender as WebView2;
if (webView != null)
@ -64,10 +64,13 @@ namespace PhotoCollector
webView.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
AddEventHandler();
webView.CoreWebView2.AddHostObjectToScript("dotnet", new WebView2Interop());
webView.CoreWebView2.Navigate(AppDbContext.getConfig("url"));
await Program.WebHostStartAsync();
}
}
public void Navigate(string url)
{
this.webView21.CoreWebView2.Navigate(url);
}
private void AddEventHandler()
{
WebView2Interop.FuncList.Add("selectPath", o =>

@ -10,7 +10,7 @@
<DebugType>full</DebugType>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<SatelliteResourceLanguages>zh-Hans</SatelliteResourceLanguages>
<Version>0.1.1</Version>
<Version>0.1.2</Version>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
@ -24,7 +24,9 @@
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.1020.30" />
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0" />
</ItemGroup>
@ -33,6 +35,9 @@
<Content Include="webview\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="wwwroot\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>

@ -1,16 +1,19 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using PhotoCollector.Data;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using System.Diagnostics;
namespace PhotoCollector
namespace PhotoCollector;
internal static class Program
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static MainForm MainForm;
public static IHost WebHost;
[STAThread]
private static void Main()
{
@ -48,7 +51,8 @@ namespace PhotoCollector
#endif
});
ApplicationConfiguration.Initialize();
Application.Run(new MainForm());
MainForm = new MainForm();
Application.Run(MainForm);
Log.Information("application exit");
}
catch (Exception ex)
@ -63,5 +67,23 @@ namespace PhotoCollector
Log.CloseAndFlush();
}
}
public static async Task WebHostStartAsync()
{
WebHost = Host.CreateDefaultBuilder()
.ConfigureHostConfiguration(configHost =>
{
configHost.SetBasePath(AppContext.BaseDirectory);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.CaptureStartupErrors(true);
webBuilder.UseSetting(WebHostDefaults.DetailedErrorsKey, "true");
webBuilder.UseContentRoot(AppContext.BaseDirectory);
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls("http://localhost:8440");
})
.Build();
await WebHost.StartAsync();
}
}

@ -0,0 +1,33 @@

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text.Encodings.Web;
using System.Text.Unicode;
namespace PhotoCollector;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
}
public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime)
{
lifetime.ApplicationStarted.Register(() =>
{
var url = app.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses.FirstOrDefault();
Program.MainForm.BeginInvoke(new EventHandler(delegate
{
Task.Delay(1000);
Program.MainForm.Navigate(url);
}));
});
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseDefaultFiles();
app.UseFileServer();
}
}

@ -0,0 +1,265 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<title>模拟接口</title>
<style>
body {
margin: 0;
padding: 0;
border: none;
outline: none;
width: 100vw;
height: 100vh;
}
:root {
--width: 358px;
--height: 441px;
}
.videoWrapper {
position: relative;
text-align: center;
display: inline-block;
width: 960px;
height: 540px;
}
.videoWrapper video {
width: 100%;
height: 100%;
}
.range {
width: var(--width);
height: var(--height);
border: 1px solid blue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.range .big {
width: 221px;
border: 1px dotted green;
position: absolute;
top: 7px;
bottom: 207px;
left: 50%;
transform: translate(-50%, 0);
}
.range .small {
width: 207px;
border: 1px dotted green;
position: absolute;
top: 21px;
bottom: 207px;
left: 50%;
transform: translate(-50%, 0);
}
</style>
</head>
<body>
<select id="select"></select>
<button id="button">拍照</button>
<button id="folderBrowser">选择目录</button>
<button id="readFile">读取图片</button>
<button id="saveFile">保存图片</button>
<button id="getConfig">读取配置</button>
<button id="setConfig">保存配置</button>
<button id="removeConfig">移除配置</button>
<button id="getConfigs">查询配置</button>
<hr />
<div class="videoWrapper">
<video id="webcam"></video>
<div class="range">
<div class="big"></div>
<div class="small"></div>
</div>
</div>
<canvas id="canvas" width="358" height="441"></canvas>
<img id="img" alt="" width="358" height="441" />
<hr />
<img id="idCard" width="102" height="126" alt="" />
<script>
var appBasePath = window.chrome.webview.hostObjects.sync.dotnet.GetAppPath();
//window.chrome.webview.postMessage({ command: "setStatus", message: `start at ${appBasePath}` });
function onIdCardRead(card) {
var img = document.getElementById('idCard');
img.src = card.image;
img.title = result.name;
}
//文件夹浏览
document.getElementById("folderBrowser").onclick = function () {
var response = window.chrome.webview.hostObjects.sync.dotnet.Action(JSON.stringify({
command: "selectPath",
path: appBasePath
}));
var result = JSON.parse(response);
if (result.code) {
alert(result.message);
}
else {
alert(`选择的文件夹:${result.path}`);
}
}
//读取文件base64
document.getElementById("readFile").onclick = function () {
var response = window.chrome.webview.hostObjects.sync.dotnet.Action(JSON.stringify({
command: 'readFile',
file: appBasePath + "asserts/test.webp"
}));
var result = JSON.parse(response);
if (result.code) {
alert(result.message);
}
else {
document.getElementById('img').src = `data:image/webp;base64,${result.base64}`;
}
}
//写入文件
document.getElementById("saveFile").onclick = function () {
var response = window.chrome.webview.hostObjects.sync.dotnet.Action(JSON.stringify({
command: 'saveFile',
file: appBasePath + "asserts/test.webp",
base64: canvas.toDataURL('image/webp')
}));
var result = JSON.parse(response);
if (result.code) {
alert(result.message);
}
else {
alert("写入文件成功");
}
};
//获取配置
document.getElementById("getConfig").onclick = function () {
var response = window.chrome.webview.hostObjects.sync.dotnet.Action(JSON.stringify({
command: 'getConfig',
key: "test"
}));
var result = JSON.parse(response);
if (result.code) {
alert(result.message);
}
else {
alert(result.value);
}
}
//查询配置
document.getElementById("getConfigs").onclick = function () {
var response = window.chrome.webview.hostObjects.sync.dotnet.Action(JSON.stringify({
command: 'getConfigs',
key: "test"
}));
var result = JSON.parse(response);
if (result.code) {
alert(result.message);
}
else {
alert(JSON.stringify(result.value));
}
}
//设置配置
document.getElementById("setConfig").onclick = function () {
var response = window.chrome.webview.hostObjects.sync.dotnet.Action(JSON.stringify({
command: 'setConfig',
key: "test",
value: `当前时间:${new Date().toLocaleString()}`
}));
var result = JSON.parse(response);
if (result.code) {
alert(result.message);
}
else {
alert("设置配置成功");
}
}
//删除配置,name和url不能删除
document.getElementById("removeConfig").onclick = function () {
var response = window.chrome.webview.hostObjects.sync.dotnet.Action(JSON.stringify({
command: 'removeConfig',
key: "test"
}));
var result = JSON.parse(response);
if (result.code) {
alert(result.message);
}
else {
alert("删除配置成功");
}
}
</script>
<script>
var width = 358;
var height = 441;
var select = document.getElementById("select");
var video = document.getElementById("webcam");
var button = document.getElementById("button");
button.onclick = function (event) {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.drawImage(video, (video.width - width) / 2, (video.height - height) / 2, width, height, 0, 0, width, height);
};
select.onchange = function (event) {
var hdConstraints = {
audio: false,
video: {
width: { min: 640, ideal: 1280, max: 1920 },
height: { min: 360, ideal: 720, max: 1080 },
deviceId: event.target.value
}
};
navigator.mediaDevices.getUserMedia(hdConstraints).then(function (mediaStream) {
video.srcObject = mediaStream;
video.addEventListener("loadedmetadata", function (e) {
video.width = e.srcElement.videoWidth;
video.height = e.srcElement.videoHeight;
//var wrapper = document.querySelector('.videoWrapper');
//wrapper.style.width = video.width + 'px';
//wrapper.style.height = video.height + 'px';
video.play();
});
}, function (err) {
console.error('getUserMediaErrorCallback')
});
};
function init() {
if (video.srcObject && video.srcObject.active) {
return;
}
navigator.mediaDevices.enumerateDevices()
.then(function (devices) {
select.innerHTML = "";
devices.forEach(function (device) {
console.log(device);
if (device.kind === 'videoinput' && device.label) {
select.insertAdjacentHTML('beforeend', `<option value="${device.deviceId}">${device.label}</option>`);
}
});
if (select.children.length) {
select.children[0].setAttribute("selected", "selected");
select.dispatchEvent(new Event('change'));
}
})
.catch(function (err) {
console.log(err.name + ": " + err.message);
});
}
//setInterval(init, 5000);
init();
</script>
</body>
</html>
Loading…
Cancel
Save