I can't English very well yet. please understand even if you can't understand me clearly.
I have huge data table in UserControl.xaml, but downscale this UserControl object showing whole in MainWindow.
I want same size datatable showing of partially UserControl in MainWindow.
Like this image display way:
<Image>
<Image.Source>
<CroppedBitmap Source="<path to source image>" SourceRect="20,20,50,50"/>
</Image.Source>
</Image>
Showing UserControl in MainWindow like a SourceRect.
If I understand you correctly, you have several options. The first way, and I think the easiest is to use ViewBox control.
1. ViewBox
The Viewbox control inherited from Decorator is used to stretch or scale a child element, but it is scaled proportionally, ie you can not set the him size such 300x100.
Example
<Viewbox Width="300"
Height="300">
<DataGrid>
...
</DataGrid>
</ViewBox>
The second way is to use a screen capture of your control, that you would like to show, and then if you want to use CroppedBitmap.
2. Capturing screen
I found a great article by Pete Brown on this subject here:
Capturing Screen Images in WPF using GDI, Win32 and a little WPF Interop Help
In this article is an example, and it looks like this:
ScreenCapture
class ScreenCapture
{
public static BitmapSource CaptureFullScreen(bool addToClipboard)
{
return CaptureRegion(
User32.GetDesktopWindow(),
(int)SystemParameters.VirtualScreenLeft,
(int)SystemParameters.VirtualScreenTop,
(int)SystemParameters.VirtualScreenWidth,
(int)SystemParameters.VirtualScreenHeight,
addToClipboard);
}
// capture a window. This doesn't do the alt-prtscrn version that loses the window shadow.
// this version captures the shadow and optionally inserts a blank (usually white) area behind
// it to keep the screen shot clean
public static BitmapSource CaptureWindow(IntPtr hWnd, bool recolorBackground, Color substituteBackgroundColor, bool addToClipboard)
{
Int32Rect rect = GetWindowActualRect(hWnd);
Window blankingWindow = null;
if (recolorBackground)
{
blankingWindow = new Window();
blankingWindow.WindowStyle = WindowStyle.None;
blankingWindow.Title = string.Empty;
blankingWindow.ShowInTaskbar = false;
blankingWindow.AllowsTransparency = true;
blankingWindow.Background = new SolidColorBrush(substituteBackgroundColor);
blankingWindow.Show();
int fudge = 20;
blankingWindow.Left = rect.X - fudge / 2;
blankingWindow.Top = rect.Y - fudge / 2;
blankingWindow.Width = rect.Width + fudge;
blankingWindow.Height = rect.Height + fudge;
}
// bring the to-be-captured window to capture to the foreground
// there's a race condition here where the blanking window
// sometimes comes to the top. Hate those. There is surely
// a non-WPF native solution to the blanking window which likely
// involves drawing directly on the desktop or the target window
User32.SetForegroundWindow(hWnd);
BitmapSource captured = CaptureRegion(
hWnd,
rect.X,
rect.Y,
rect.Width,
rect.Height,
true);
if (blankingWindow != null)
blankingWindow.Close();
return captured;
}
// capture a region of the full screen
public static BitmapSource CaptureRegion(int x, int y, int width, int height, bool addToClipboard)
{
return CaptureRegion(User32.GetDesktopWindow(), x, y, width, height, addToClipboard);
}
// capture a region of a the screen, defined by the hWnd
public static BitmapSource CaptureRegion(
IntPtr hWnd, int x, int y, int width, int height, bool addToClipboard)
{
IntPtr sourceDC = IntPtr.Zero;
IntPtr targetDC = IntPtr.Zero;
IntPtr compatibleBitmapHandle = IntPtr.Zero;
BitmapSource bitmap = null;
try
{
// gets the main desktop and all open windows
sourceDC = User32.GetDC(User32.GetDesktopWindow());
//sourceDC = User32.GetDC(hWnd);
targetDC = Gdi32.CreateCompatibleDC(sourceDC);
// create a bitmap compatible with our target DC
compatibleBitmapHandle = Gdi32.CreateCompatibleBitmap(sourceDC, width, height);
// gets the bitmap into the target device context
Gdi32.SelectObject(targetDC, compatibleBitmapHandle);
// copy from source to destination
Gdi32.BitBlt(targetDC, 0, 0, width, height, sourceDC, x, y, Gdi32.SRCCOPY);
// Here's the WPF glue to make it all work. It converts from an
// hBitmap to a BitmapSource. Love the WPF interop functions
bitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
compatibleBitmapHandle, IntPtr.Zero, Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
if (addToClipboard)
{
//Clipboard.SetImage(bitmap); // high memory usage for large images
IDataObject data = new DataObject();
data.SetData(DataFormats.Dib, bitmap, false);
Clipboard.SetDataObject(data, false);
}
}
catch (Exception ex)
{
throw new ScreenCaptureException(string.Format("Error capturing region {0},{1},{2},{3}", x, y, width, height), ex);
}
finally
{
Gdi32.DeleteObject(compatibleBitmapHandle);
User32.ReleaseDC(IntPtr.Zero, sourceDC);
User32.ReleaseDC(IntPtr.Zero, targetDC);
}
return bitmap;
}
// this accounts for the border and shadow. Serious fudgery here.
private static Int32Rect GetWindowActualRect(IntPtr hWnd)
{
Win32Rect windowRect = new Win32Rect();
Win32Rect clientRect = new Win32Rect();
User32.GetWindowRect(hWnd, out windowRect);
User32.GetClientRect(hWnd, out clientRect);
int sideBorder = (windowRect.Width - clientRect.Width)/2 + 1;
// sooo, yeah.
const int hackToAccountForShadow = 4;
Win32Point topLeftPoint = new Win32Point(windowRect.Left - sideBorder, windowRect.Top - sideBorder);
//User32.ClientToScreen(hWnd, ref topLeftPoint);
Int32Rect actualRect = new Int32Rect(
topLeftPoint.X,
topLeftPoint.Y,
windowRect.Width + sideBorder * 2 + hackToAccountForShadow,
windowRect.Height + sideBorder * 2 + hackToAccountForShadow);
return actualRect;
}
}
Example of using:
private void CaptureRegionButton_Click(object sender, RoutedEventArgs e)
{
CapturedImage.Source = ScreenCapture.CaptureRegion(100, 100, 500, 500, true);
}
private void CaptureScreenButton_Click(object sender, RoutedEventArgs e)
{
CapturedImage.Source = ScreenCapture.CaptureFullScreen(true);
}
Related
I'm seeing some strange behaviour from WPF. I have a form with three buttons on it. One button should make the window fullscreen, one should center it on the monitor its currently on, the third button should restore the window to its normal position.
The XAML is
<Window x:Class="TestRestore.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
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:TestRestore"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" ResizeMode="CanResizeWithGrip" WindowStartupLocation="CenterScreen">
<Grid>
<Button Content="Max" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="94" Click="max_click" Name="max_button"/>
<Button Content="Center" HorizontalAlignment="Left" Margin="10,35,0,0" VerticalAlignment="Top" Width="94" Click="center_click" Name="center_button"/>
<Button Content="Restore" HorizontalAlignment="Left" Margin="227,143,0,0" VerticalAlignment="Top" Width="75" Click="restore_click" Name="restore_button" IsEnabled="False"/>
</Grid>
</Window>
and the code is below. The strange behaviour is that when I maximize, and then restore the window, the position is correctly restored but the window still thinks it's maximized (the maximize button looks like a restore button and you can't resize the window even though ResizeMode has been set to CanResizeWithGrip).
When the maximized window has been restored, and it thinks its still maximized even though the window position isn't maximized, just moving the window manually by dragging the title bar is enough to cause it to correct itself back to non-maximized mode.
Also, if I maximize then restore the window and then maximize it again without moving it, the maximized window position is incorrect (not in the top left).
And the mystery deepens. If I maximize then restore the window, then press alt, then press down (to get the window menu) and select 'Move' and then move the window around with the keyboard, it stays stuck in 'bogus not-mazimized mode' even though the window is being moved, so it seems the only way to unstick it is to move it with the mouse.
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace TestRestore
{
public partial class MainWindow : Window
{
WindowStyle old_window_style;
WindowState old_window_state;
double old_left;
double old_top;
double old_width;
double old_height;
public MainWindow()
{
InitializeComponent();
}
// remember position, style and state
private void SaveWindowPos()
{
old_window_style = WindowStyle;
old_window_state = WindowState;
old_left = Left;
old_top = Top;
old_width = Width;
old_height = Height;
max_button.IsEnabled = false;
center_button.IsEnabled = false;
restore_button.IsEnabled = true;
}
// put position, style and state back
private void RestoreWindowPos()
{
WindowStyle = old_window_style;
WindowState = old_window_state;
ResizeMode = ResizeMode.CanResizeWithGrip;
Left = old_left;
Top = old_top;
Width = old_width;
Height = old_height;
max_button.IsEnabled = true;
center_button.IsEnabled = true;
restore_button.IsEnabled = false;
}
// make it centered or fullscreen
private void SetActivePos(bool full_screen)
{
SaveWindowPos();
Hide();
if (full_screen)
{
ResizeMode = ResizeMode.NoResize;
WindowStyle = WindowStyle.None;
WindowState = WindowState.Maximized;
}
else
{
Size s = new Size(800, 600);
Point p = CenterRectInMonitor(this, s);
Left = p.X;
Top = p.Y;
Width = s.Width;
Height = s.Height;
ResizeMode = ResizeMode.NoResize;
WindowState = WindowState.Normal;
}
Show();
}
private void restore_click(object sender, RoutedEventArgs e)
{
Hide();
RestoreWindowPos();
Show();
}
private void max_click(object sender, RoutedEventArgs e)
{
SetActivePos(true);
}
private void center_click(object sender, RoutedEventArgs e)
{
SetActivePos(false);
}
// interop
public const Int32 MONITOR_DEFAULTTOPRIMARY = 0x00000001;
public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow(IntPtr handle, Int32 flags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi);
// size of a device name string
private const int CCHDEVICENAME = 32;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct MonitorInfoEx
{
public int Size;
public RectStruct Monitor;
public RectStruct WorkArea;
public uint Flags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
public string DeviceName;
public void Init()
{
this.Size = 40 + 2 * CCHDEVICENAME;
this.DeviceName = string.Empty;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct RectStruct
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public int Width
{
get
{
return Right - Left;
}
}
public int Height
{
get
{
return Bottom - Top;
}
}
}
public static MonitorInfoEx GetMonitorFromWindow(Window w)
{
var hwnd = new WindowInteropHelper(w).EnsureHandle();
var monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
MonitorInfoEx monitor_info = new MonitorInfoEx();
monitor_info.Init();
GetMonitorInfo(monitor, ref monitor_info);
return monitor_info;
}
// work out how a rect of 'Size size' should be centered on the monitor containing 'Window w'
public static Point CenterRectInMonitor(Window w, Size size)
{
var source = PresentationSource.FromVisual(w);
double x_scale = source.CompositionTarget.TransformToDevice.M11;
double y_scale = source.CompositionTarget.TransformToDevice.M22;
var width = size.Width * x_scale;
var height = size.Height * y_scale;
var monitor_info = GetMonitorFromWindow(w);
Size s = new Size(monitor_info.Monitor.Width, monitor_info.Monitor.Height);
Point p = new Point(monitor_info.Monitor.Left, monitor_info.Monitor.Top);
Point c = new Point(p.X + s.Width / 2, p.Y + s.Height / 2);
return new Point((c.X - width / 2) / x_scale, (c.Y - height / 2) / y_scale);
}
}
}
I don't have a complete answer for you. However you will find that your code starts working a lot better once you remove the Hide() and Show() calls.
private void restore_click(object sender, RoutedEventArgs e)
{
// Hide();
RestoreWindowPos();
// Show();
}
I'm sure you put this in to reduce flicker, but what I think is happening is that the Hide() and Show() calls are flipping the WS_VISIBLE bit in the window style word of the underlying OS window which is the same word which contains the WS_MAXIMIZE and WS_BORDER and some other things that you are manipulating. See https://msdn.microsoft.com/en-us/library/windows/desktop/ms632600(v=vs.85).aspx
It would take more research to figure out what is exactly going on, but the fundamental problem I believe is a "leaky abstraction". Your code sets top, left, style and state as if these were independent uncoupled variables. But they are not! To set left, the OS SetWindowPos() function must be called which requires not the upper left coordinate, the window size, the Z order as well as visibility flags and whether the windows is maximized! See https://msdn.microsoft.com/en-us/library/windows/desktop/ms633545(v=vs.85).aspx. So each time you set one of these "independent" variables you are pounding SetWindowPos(). This API call harks back to the bad old days when CPU cycles were precious and you need to pack as much functionality as possible into each API call.
Ironically this is making your code very inefficient. I think the thing to do to straighten this out is to bypass the leaking abstraction of System.Windows.Window and call SetWindowPos and possibility other API functions directly from user32.dll. Then things will be a lot more predicable.
I would like to draw some rectangle on top of certain area of a window in WPF application. The problem is how to do it in such way that during window's size change the figure gets resized proportionally too?
Any hints highly appreciated.
You could do something like that in your window's code behind file:
//Constructor
public MyWindow() {
InitializeComponent();
//Register the SizeChanged-event
this.SizeChanged += OnSizeChanged;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
var parentWindow = (Window)sender;
var sizeOfRectangle = CalculateSizeOfRectangle(parentWindow.actualHeight, parentWindow.actualWidth);
// assuming you have a reference to your colored rectangle here (e.g. Name defined in XAML code)
ColoredRectangle.Width = sizeOfRectangle.Width;
ColoredRectangle.Height = sizeOfRectangle.Height;
}
private Size CalculateSizeOfRectangle(double height, double width)
{
int height = ....; // Calculate height here
int width = ....; // Calculate width her
return new Size(width, height);
}
I've got a fairly straightforward pixel shader—set alpha channel to zero and return.
sampler2D tex : register(s0);
float4 PS(float2 uv : TEXCOORD) : COLOR
{
float4 color = tex2D(tex, uv);
color.a = 0;
return color;
}
I'd assume this would cause the image it's applied to to be completely invisible. However that's not what appears to be happening. Instead, the resulting image will become invisible over a white background, but over a black background it'll be unchanged. It appears that this shader is somehow causing an "add" function to be called between the foreground and the background.
For example, the following code loads a foreground and background image, applies the above shader effect to the foreground, renders them to a bitmap, and writes the bitmap to file.
public sealed partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
void Button_Click(object sender, RoutedEventArgs e)
{
const int width = 1024;
const int height = 768;
var sz = new Size(width, height);
var background = new Image { Source = new BitmapImage(new Uri(#"c:\background.jpg")) };
background.Measure(sz);
background.Arrange(new Rect(sz));
var foreground = new Image { Source = new BitmapImage(new Uri(#"c:\foreground.jpg")), Effect = new Alpha() };
foreground.Measure(sz);
foreground.Arrange(new Rect(sz));
var target = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default);
target.Render(background);
target.Render(foreground);
var jpg = new JpegBitmapEncoder();
jpg.Frames.Add(BitmapFrame.Create(target));
using (var fileStream = File.OpenWrite(#"c:\output.jpg"))
{
jpg.Save(fileStream);
}
}
}
// Standard ShaderEffect stuff here, nothing exciting.
public sealed class Alpha : ShaderEffect
{
static readonly PixelShader Shader = new PixelShader{UriSource = new Uri("pack://application:,,,/Alpha.ps", UriKind.RelativeOrAbsolute)};
public static readonly DependencyProperty InputProperty = RegisterPixelShaderSamplerProperty("Input", typeof(Alpha), 0);
public Alpha()
{
PixelShader = Shader;
UpdateShaderValue(InputProperty);
}
public Brush Input
{
get { return (Brush)GetValue(InputProperty); }
set { SetValue(InputProperty, value); }
}
}
This produces the following when applied to two of the Win7 sample pictures:
This is the same behavior I see on the screen when I apply the effect to one Image in XAML, with another Image or anything else behind it.
Note the image is the same if foreground and background are reversed, so if it's not "add", it's at least something commutative. I think it's "add".
Computers are usually right, so I assume this is user error, but why is setting alpha to zero not giving me a transparent image? And how do I get a transparent image if so? (I obviously want to do something more complex with the shader eventually (specifically greenscreen), but to get that to work I have to get this shader to work first, so don't just say "Set the Opacity property").
Gah, stackoverflow is better than google. The top "related question" had the answer. Handling alpha channel in WPF pixel shader effect
In Win32 API, function SetWindowPos provided an easy way to move and resize window at once.
However, in WPF class Window doesn't have a method like SetWindowPos. So I must code like the following:
this.Left += e.HorizontalChange;
this.Top += e.VerticalChange;
this.Width = newWidth;
this.Height = newHeight;
Of course, it works well, but it's not simple. And it looks dirty.
How can i move a window and resize at once?
Is there an API?
I know you've already solved your problem, but I'll post a solution that I found in case it helps others.
Basically, You must declare that SetWindowsPos as an imported function from Win32 this is the signature
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);
The function needs the hWnd of your window, in order to get it you can add an handler on the initialization of your windows (for example you could listen for the "SourceInitialized" event) and store that value in a private member of the class:
hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
WPF manages device independent pixels, so you needs even a converter from dip to real pixel for your screen. This is done with these lines:
var source = PresentationSource.FromVisual(this);
Matrix transformToDevice = source.CompositionTarget.TransformToDevice;
Point[] p = new Point[] { new Point(this.Left + e.HorizontalChange, this.Top), new Point(this.Width - e.HorizontalChange, this.Height) };
transformToDevice.Transform(p);
Finally you can call SetWindowsPos:
SetWindowPos(this.hwndSource.Handle, IntPtr.Zero, Convert.ToInt32(p[0].X), Convert.ToInt32(p[0].Y), Convert.ToInt32(p[1].X), Convert.ToInt32(p[1].Y), SetWindowPosFlags.SWP_SHOWWINDOW);
Sources:
Win32 SetWindowPos
WPF Graphics Rendering
You could wrap your code in a helper method. Just like this:
public static class WindowExtensions {
public static void MoveAndResize( this Window value, double horizontalChange, double verticalChange, double width, double height ) {
value.Left += horizontalChange;
value.Top += verticalChange;
value.Width = width;
value.Height = height;
}
}
So your calling code looks like this:
this.MoveAndResize( 10, 10, 1024, 768 );
I've left off namespace and using declaration, keep that in mind when copying.
Edit:
You could also use the API. Personally I stick with the managed code unless I really need to use the API. But that is up to you.
How to get current mouse coordination on the screen?
I know only Mouse.GetPosition() which get mousePosition of element, but I want to get the coordination without using element.
Or in pure WPF use PointToScreen.
Sample helper method:
// Gets the absolute mouse position, relative to screen
Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window));
To follow up on Rachel's answer.
Here's two ways in which you can get Mouse Screen Coordinates in WPF.
1.Using Windows Forms. Add a reference to System.Windows.Forms
public static Point GetMousePositionWindowsForms()
{
var point = Control.MousePosition;
return new Point(point.X, point.Y);
}
2.Using Win32
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
var w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
Do you want coordinates relative to the screen or the application?
If it's within the application just use:
Mouse.GetPosition(Application.Current.MainWindow);
If not, I believe you can add a reference to System.Windows.Forms and use:
System.Windows.Forms.Control.MousePosition;
If you try a lot of these answers out on different resolutions, computers with multiple monitors, etc. you may find that they don't work reliably. This is because you need to use a transform to get the mouse position relative to the current screen, not the entire viewing area which consists of all your monitors. Something like this...(where "this" is a WPF window).
var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var mouse = transform.Transform(GetMousePosition());
public System.Windows.Point GetMousePosition()
{
var point = Forms.Control.MousePosition;
return new Point(point.X, point.Y);
}
This works without having to use forms or import any DLLs:
using System.Windows;
using System.Windows.Input;
/// <summary>
/// Gets the current mouse position on screen
/// </summary>
private Point GetMousePosition()
{
// Position of the mouse relative to the window
var position = Mouse.GetPosition(Window);
// Add the window position
return new Point(position.X + Window.Left, position.Y + Window.Top);
}
You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(out POINT pPoint);
Point is a light struct. It contains only X, Y fields.
public MainWindow()
{
InitializeComponent();
DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
dt.Tick += new EventHandler(timer_tick);
dt.Interval = new TimeSpan(0,0,0,0, 50);
dt.Start();
}
private void timer_tick(object sender, EventArgs e)
{
POINT pnt;
GetCursorPos(out pnt);
current_x_box.Text = (pnt.X).ToString();
current_y_box.Text = (pnt.Y).ToString();
}
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds.
TimeSpan(50); //ticks
If you're looking for a 1 liner, this does well.
new Point(Mouse.GetPosition(mWindow).X + mWindow.Left, Mouse.GetPosition(mWindow).Y + mWindow.Top)
The + mWindow.Left and + mWindow.Top makes sure the position is in the right place even when the user drags the window around.
Mouse.GetPosition(mWindow) gives you the mouse position relative to the parameter of your choice.
mWindow.PointToScreen() convert the position to a point relative to the screen.
So mWindow.PointToScreen(Mouse.GetPosition(mWindow)) gives you the mouse position relative to the screen, assuming that mWindow is a window(actually, any class derived from System.Windows.Media.Visual will have this function), if you are using this inside a WPF window class, this should work.
I wanna use this code
Point PointA;
private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e) {
PointA = e.MouseDevice.GetPosition(sender as UIElement);
}
private void Button_Click(object sender, RoutedEventArgs e) {
// use PointA Here
}