Skip to content
This repository has been archived by the owner on Aug 17, 2024. It is now read-only.

Commit

Permalink
调整OCR模式,使用固定透明窗口截图
Browse files Browse the repository at this point in the history
  • Loading branch information
Isayama-Kagura committed Feb 22, 2023
1 parent 48b7f58 commit 22a2ddf
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 267 deletions.
23 changes: 11 additions & 12 deletions TsubakiTranslator/ScreenshotWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TsubakiTranslator"
mc:Ignorable="d"
Title="Screenshot" WindowStyle="None" Topmost="True" KeyDown="Window_KeyDown" AllowsTransparency="True" Background="#02FFFFFF" WindowStartupLocation="CenterScreen" Height="800" Width="800" Loaded="Window_Loaded" MouseUp="Window_MouseUp" MouseMove="Window_MouseMove" MouseDown="Window_MouseDown" Cursor="Cross" Padding="0" >
<Grid x:Name="gridMain" Margin="0">
<Border x:Name="borderCapture" BorderBrush="#FF6D29A4" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="Collapsed" Background="#3F2948C0" Padding="0">
<Viewbox MaxWidth="400" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock x:Name="textConfirmRegion" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold" Foreground="White" Visibility="Collapsed" MaxWidth="400">
右键确认截图区域,按Esc退出
</TextBlock>
</Viewbox>
</Border>
<Label x:Name="labelHeader" Content="选择窗口或左键选区" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="24" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="WhiteSmoke"/>
xmlns:local="clr-namespace:TsubakiTranslator" ShowInTaskbar="False"
mc:Ignorable="d" Background="#01000000" WindowStyle="None" AllowsTransparency="True" Cursor="SizeAll"
MouseLeftButtonDown="Window_MouseLeftButtonDown" Topmost="True"
Title="ScreenshotWindowTest" Height="450" Width="800">

<WindowChrome.WindowChrome>
<WindowChrome CaptionHeight="0" ResizeBorderThickness="15"/>
</WindowChrome.WindowChrome>
<Grid>
<Rectangle Stroke="#b71c1c" StrokeThickness="2"
StrokeDashArray="10 5" SnapsToDevicePixels="True" />
</Grid>
</Window>
257 changes: 45 additions & 212 deletions TsubakiTranslator/ScreenshotWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,247 +1,80 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Interop;
using TsubakiTranslator.BasicLibrary;

namespace TsubakiTranslator
{
/// <summary>
/// Interaction logic for ScreenshotWindow.xaml
/// ScreenshotWindowTest.xaml 的交互逻辑
/// </summary>
public partial class ScreenshotWindow : Window
{
public static ScreenshotWindow Current { get; set; }
private Bitmap BackgroundImage { get; set; }
private System.Windows.Point StartPoint { get; set; }
private double DpiScale { get; set; } = 1;
private bool ManualRegionSelection { get; set; } = false;

private static Bitmap bitmap;
public static Bitmap Bitmap { get => bitmap; }

private static Rect drawRegion;
public static Rect DrawRegion { get => drawRegion; }
private ScreenshotWindow()
public ScreenshotWindow()
{
InitializeComponent();
Current = this;
}
public static async Task Start()
{
var capture = new ScreenshotWindow();
//MainWindow.Current.WindowState = WindowState.Minimized;

await Task.Delay(500);
var screen = SystemInformation.VirtualScreen;
capture.BackgroundImage = BasicLibrary.ScreenshotHandler.GetCapture(new Rect(screen.Left, screen.Top, screen.Width, screen.Height));


capture.ShowDialog();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DpiScale = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.M11;
labelHeader.Visibility = Visibility.Visible;
borderCapture.Visibility = Visibility.Visible;
this.Width = SystemParameters.VirtualScreenWidth;
this.Height = SystemParameters.VirtualScreenHeight;
this.Left = SystemParameters.VirtualScreenLeft;
this.Top = SystemParameters.VirtualScreenTop;

using (var ms = new MemoryStream())
{
BackgroundImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
var bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.EndInit();
bi.Freeze();
gridMain.Background = new ImageBrush(bi);
}

FrameWindowUnderCursor();
this.Activate();
}
//private void Window_Closed(object sender, EventArgs e)
//{
// if (CaptureControls.Current?.IsVisible != true)
// {
// MainWindow.Current.WindowState = WindowState.Normal;
// if (Editor.Current?.IsVisible == true)
// {
// Editor.Current.Activate();
// }
// }
//}
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.Key == Key.Escape)
/* 如何在Window.ResizeMode属性为CanResize的时候,阻止窗口拖动到屏幕边缘自动最大化。
(When the Window.ResizeMode property is CanResize,
when the window is dragged to the edge of the screen,
it prevents the window from automatically maximizing.)*/
if (e.ChangedButton == MouseButton.Left)
{
if (textConfirmRegion.IsVisible)
{
textConfirmRegion.Visibility = Visibility.Collapsed;
ManualRegionSelection = false;
FrameWindowUnderCursor();
}
else
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
bitmap = null;
this.Close();
}
}
}
var windowMode = this.ResizeMode;
if (this.ResizeMode != ResizeMode.NoResize)
{
this.ResizeMode = ResizeMode.NoResize;
}

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
this.UpdateLayout();

if (e.ChangedButton == MouseButton.Left)
{
if (textConfirmRegion.IsVisible)
{
textConfirmRegion.Visibility = Visibility.Collapsed;
}
StartPoint = e.GetPosition(this);
}

}
/* 当点击拖拽区域的时候,让窗口跟着移动
(When clicking the drag area, make the window follow) */
DragMove();

private async void Window_MouseUp(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Right)
{
if (textConfirmRegion.IsVisible)
{
try
{
await HideAllButBackground();
//BasicLibrary.Screenshot.SaveCapture(BasicLibrary.Screenshot.GetCapture(GetDrawnRegion(true)));

//两种OCR模式的不同处理
if (App.OtherConfig.IsAutoScreenshot)
{
drawRegion = GetDrawnRegion(true);
}
else
{
bitmap = BasicLibrary.ScreenshotHandler.GetCapture(GetDrawnRegion(true));
}

this.Close();
}
catch (Exception ex)

if (this.ResizeMode != windowMode)
{
System.Windows.MessageBox.Show(ex.Message, "Capture Error", MessageBoxButton.OK, MessageBoxImage.Error);
//MainWindow.Current.WriteToLog(ex);
this.Close();
this.ResizeMode = windowMode;
}

this.UpdateLayout();
}
}
else if (e.ChangedButton == MouseButton.Left)
{
ManualRegionSelection = true;
textConfirmRegion.Visibility = Visibility.Visible;
}
}

private void Window_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
ManualRegionSelection = true;
var pos = e.GetPosition(this);
var left = Math.Min(pos.X, StartPoint.X);
var top = Math.Min(pos.Y, StartPoint.Y);
var width = Math.Abs(StartPoint.X - pos.X);
var height = Math.Abs(StartPoint.Y - pos.Y);
borderCapture.Margin = new Thickness(left, top, 0, 0);
borderCapture.Width = width;
borderCapture.Height = height;
}
}
public Rect GetDrawnRegion(bool scaleWithDPI)
{
if (scaleWithDPI)
{
return new Rect(Math.Round(borderCapture.Margin.Left * DpiScale + SystemInformation.VirtualScreen.Left, 0),
Math.Round(borderCapture.Margin.Top * DpiScale + SystemInformation.VirtualScreen.Top, 0),
Math.Round(borderCapture.Width * DpiScale, 0),
Math.Round(borderCapture.Height * DpiScale, 0));
}
else
{
return new Rect(Math.Round(borderCapture.Margin.Left + SystemInformation.VirtualScreen.Left, 0),
Math.Round(borderCapture.Margin.Top + SystemInformation.VirtualScreen.Top, 0),
Math.Round(borderCapture.Width, 0),
Math.Round(borderCapture.Height, 0));
}
}
private async Task HideAllButBackground()
{
textConfirmRegion.Visibility = Visibility.Collapsed;
labelHeader.Visibility = Visibility.Collapsed;
borderCapture.Visibility = Visibility.Collapsed;
do
{
await Task.Delay(100);
}
while (labelHeader.IsVisible || textConfirmRegion.IsVisible || borderCapture.IsVisible);
}
private async void FrameWindowUnderCursor()


public Bitmap TakeScreenshot()
{
var point = new System.Drawing.Point();
var rect = new User32.RECT();
var screen = SystemInformation.VirtualScreen;
var winList = new List<IntPtr>();
var thisHandle = new System.Windows.Interop.WindowInteropHelper(this).Handle;
var shellHandle = User32.GetShellWindow();
var desktopHandle = User32.GetDesktopWindow();
while (this.IsVisible && ManualRegionSelection == false)
{
User32.GetCursorPos(out point);
winList.Clear();
var devenv = System.Diagnostics.Process.GetProcesses().FirstOrDefault(proc => proc.MainWindowTitle.Contains("CleanShot") && proc.MainWindowTitle.Contains("Microsoft"));
User32.EnumWindows((hWin, lParam) =>
{
if (hWin == thisHandle || hWin == shellHandle || hWin == desktopHandle || !User32.IsWindowVisible(hWin))
{
return true;
}
User32.GetWindowRect(hWin, out rect);
if (rect.Width == screen.Width && rect.Height == screen.Height)
{
return true;
}
if (rect.Left < point.X && rect.Top < point.Y && rect.Right > point.X && rect.Bottom > point.Y)
{
winList.Add(hWin);
}
return true;
}, IntPtr.Zero);
if (winList.Count > 0)
{
WindowInteropHelper helper = new WindowInteropHelper(this);
User32.RECT rect1;
User32.GetWindowRect(HwndSource.FromHwnd(helper.Handle).Handle, out rect1);

User32.GetWindowRect(winList.First(), out rect);
}
else
{
User32.GetWindowRect(shellHandle, out rect);
}
borderCapture.Margin = new Thickness(rect.Left - screen.Left, rect.Top - screen.Top, 0, 0);
borderCapture.Width = rect.Width;
borderCapture.Height = rect.Height;
await Task.Delay(100);
}
}
// get te hDC of the target window
//IntPtr hdcSrc = User32.GetWindowDC(hWnd);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(HwndSource.FromHwnd(helper.Handle).Handle, out windowRect);

var rect = new Rect(Math.Round((double)windowRect.Left, 0),
Math.Round((double)windowRect.Top, 0),
Math.Round((double)windowRect.Width, 0),
Math.Round((double)windowRect.Height, 0));

Bitmap image = ScreenshotHandler.GetCapture(rect);

//image.Save(@"C:\Users\HP\Desktop\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
return image;
}

}
}
Loading

0 comments on commit 22a2ddf

Please sign in to comment.