标签存档: Windows Programing

How to set WPF window position according to DPI settings

Vista中当DPI设置改变的时候,屏幕的尺寸会改变,如果WPF窗口的位置是具体像素值偏移的,就需要根据当前的DPI配置进行相应的调整。

可以得到的系统参数(System Parameters we can get from WPF):

System.Windows.Forms.SystemInformation.WorkingArea (Width, Height)

Use WorkingArea to determine the bounds of the screen that can be used by applications. The working area is the portion of the screen not hidden by the operating system tray and other top-level windows that are docked to the Windows desktop.

工作区域的宽度、高度(高度不包括任务栏)

System.Windows.SystemParameters (PrimaryScreenWidth, PrimaryScreenHeight)

Gets a value that indicates the screen width/height, in pixels, of the primary display monitor.

屏幕区域的宽度、高度

网上搜罗来的解决办法:

Solution 1:

Get the current DPI value in WPF, and scale the width/height in pixels.

在WPF程序中取得当前DPI的设置,计算出像素宽度/高度的缩放数值

PresentationSource source = PresentationSource.FromVisual(this);

if (source != null)
{
dpiX = 96.0 * source.CompositionTarget.TransformToDevice.M11;

dpiY = 96.0 * source.CompositionTarget.TransformToDevice.M22;
}

Solution 2:

Using System.Windows.SystemParameters (PrimaryScreenWidth, PrimaryScreenHeight)

注意PrimaryScreenWidth, PrimaryScreenHeight这两个参数得到的像素数值本来就是经过DPI换算过的,但是请注意PrimaryScreenHeight的高度包括TaskBar。

WPF textblock Run之间的自动填充的空格

代码:
<TextBlock>
<Run Foreground=”你确定要删除” Text=”Text”/>
<Run Foreground=”配置名称” Text=”Block”/>
<Run Text=”?” />
</TextBlock>

编译后,“?”前面会自动加上一个空格。这个空格是由于XAML(其实也就是XML)解析的时候的特殊空白字符处理规则(special
whitespace handling rules
)造成的。
去掉这个空格的最简单方法是:把上面的三个Run紧挨着写在同一行上:
<TextBlock>
<Run Foreground=”你确定要删除” Text=”Text”/><Run Foreground=”配置名称” Text=”Block”/><Run Text=”?” />
</TextBlock>

Canonical URL by SEO No Duplicate WordPress Plugin