So I have the following code:
#region Dropshadow
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
int nLeftRect,
int nTopRect,
int nRightRect,
int nBottomRect,
int nWidthEllipse,
int nHeightEllipse
);
[DllImport("dwmapi.dll")]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
[DllImport("dwmapi.dll")]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
[DllImport("dwmapi.dll")]
public static extern int DwmIsCompositionEnabled(ref int pfEnabled);
private bool m_aeroEnabled;
public struct MARGINS
{
public int leftWidth;
public int rightWidth;
public int topHeight;
public int bottomHeight;
}
protected override CreateParams CreateParams {
get {
m_aeroEnabled = CheckAeroEnabled();
CreateParams cp = base.CreateParams;
if (!m_aeroEnabled) {
cp.ClassStyle |= 0x00020000;
}
return cp;
}
}
private bool CheckAeroEnabled()
{
if (Environment.OSVersion.Version.Major >= 6) {
int enabled = 0;
DwmIsCompositionEnabled(ref enabled);
return (enabled == 1) ? true : false;
}
return false;
}
protected override void WndProc(ref Message m)
{
switch (m.Msg) {
case 0x0085:
if (m_aeroEnabled) {
int v = 2;
DwmSetWindowAttribute(Handle, 2, ref v, 4);
MARGINS margins = new MARGINS() {
bottomHeight = 1,
leftWidth = 0,
rightWidth = 0,
topHeight = 0
};
DwmExtendFrameIntoClientArea(Handle, ref margins);
}
break;
default:
break;
}
base.WndProc(ref m);
}
#endregion
This makes a Dropshadow using GDI.
The only issue however, is I had to make it keep a 1 pixel height border on the top (it can be any edge, just top is hardest to notice on my app).
This makes a line on my app at the top essentially degrading viewing experience.
Is it possible to do this with no border at all?
(The bottomHeight = 1 code is where its all about. If I set it to 0, and topHeight to 1, the line will be on the bottom. Setting all of them to 0, shows no dropshadow at all.)
Turns out, its to do with my padding, I need to leave 1 pixel line empty on atleast 1 edge for the Dropshadow to work. I chose to use Padding to make that 1 pixel line and I set the top padding to 1. This sets the line at the top. The bottomHeight = 1 doesnt matter at all. It's just there as it requires atleast one of them to be non 0.
If I remove the Padding and Top Line etc. And in the CreateParams overide, if I remove the aero enabled check, it shows a dropshadow similar like this:
This is a Form class that uses DWM to render it's borders/shadow.
As described, you need to register an Attribute, DWMWINDOWATTRIBUTE, and the related Policy, DWMNCRENDERINGPOLICY, settings it's value to Enabled.
Then set the attribute with DwmSetWindowAttribute() and the desired effect with DwmExtendFrameIntoClientArea(), DwmEnableBlurBehindWindow() and so on.
All the declarations needed are here.
This is the Form class (named "Borderless", in a spark of creativity).
I tried to make it look like what you already have posted, to minimize the "impact".
The Form is a standard WinForms Form with FormBorderStyle = None.
public partial class Borderless : Form
{
public Borderless() => InitializeComponent();
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
WinApi.Dwm.DWMNCRENDERINGPOLICY Policy = WinApi.Dwm.DWMNCRENDERINGPOLICY.Enabled;
WinApi.Dwm.WindowSetAttribute(this.Handle, WinApi.Dwm.DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)Policy);
if (DWNCompositionEnabled()) { WinApi.Dwm.WindowBorderlessDropShadow(this.Handle, 2); }
//if (DWNCompositionEnabled()) { WinApi.Dwm.WindowEnableBlurBehind(this.Handle); }
//if (DWNCompositionEnabled()) { WinApi.Dwm.WindowSheetOfGlass(this.Handle); }
}
private bool DWNCompositionEnabled() => (Environment.OSVersion.Version.Major >= 6)
? WinApi.Dwm.IsCompositionEnabled()
: false;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case (int)WinApi.WinMessage.WM_DWMCOMPOSITIONCHANGED:
{
WinApi.Dwm.DWMNCRENDERINGPOLICY Policy = WinApi.Dwm.DWMNCRENDERINGPOLICY.Enabled;
WinApi.Dwm.WindowSetAttribute(this.Handle, WinApi.Dwm.DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)Policy);
WinApi.Dwm.WindowBorderlessDropShadow(this.Handle, 2);
m.Result = (IntPtr)0;
}
break;
default:
break;
}
base.WndProc(ref m);
}
}
These are all the declarations needed, plus others that might become useful.
Note that I only use the internal attribute form Win32 APIs, which are called using helpr methods.
It's a partial class because the Winapi class is a extensive class library. You can change it to whatever you are used to.
I suggest to keep the [SuppressUnmanagedCodeSecurityAttribute]
attribute for the Win32 APIs declarations.
public partial class WinApi
{
public enum WinMessage : int
{
WM_DWMCOMPOSITIONCHANGED = 0x031E, //The system will send a window the WM_DWMCOMPOSITIONCHANGED message to indicate that the availability of desktop composition has changed.
WM_DWMNCRENDERINGCHANGED = 0x031F, //WM_DWMNCRENDERINGCHANGED is called when the non-client area rendering status of a window has changed. Only windows that have set the flag DWM_BLURBEHIND.fTransitionOnMaximized to true will get this message.
WM_DWMCOLORIZATIONCOLORCHANGED = 0x0320, //Sent to all top-level windows when the colorization color has changed.
WM_DWMWINDOWMAXIMIZEDCHANGE = 0x0321 //WM_DWMWINDOWMAXIMIZEDCHANGE will let you know when a DWM composed window is maximized. You also have to register for this message as well. You'd have other windowd go opaque when this message is sent.
}
public class Dwm
public enum DWMWINDOWATTRIBUTE : uint
{
NCRenderingEnabled = 1, //Get only atttribute
NCRenderingPolicy, //Enable or disable non-client rendering
TransitionsForceDisabled,
AllowNCPaint,
CaptionButtonBounds,
NonClientRtlLayout,
ForceIconicRepresentation,
Flip3DPolicy,
ExtendedFrameBounds,
HasIconicBitmap,
DisallowPeek,
ExcludedFromPeek,
Cloak,
Cloaked,
FreezeRepresentation
}
public enum DWMNCRENDERINGPOLICY : uint
{
UseWindowStyle, // Enable/disable non-client rendering based on window style
Disabled, // Disabled non-client rendering; window style is ignored
Enabled, // Enabled non-client rendering; window style is ignored
};
// Values designating how Flip3D treats a given window.
enum DWMFLIP3DWINDOWPOLICY : uint
{
Default, // Hide or include the window in Flip3D based on window style and visibility.
ExcludeBelow, // Display the window under Flip3D and disabled.
ExcludeAbove, // Display the window above Flip3D and enabled.
};
public struct MARGINS
{
public int leftWidth;
public int rightWidth;
public int topHeight;
public int bottomHeight;
public MARGINS(int LeftWidth, int RightWidth, int TopHeight, int BottomHeight)
{
leftWidth = LeftWidth;
rightWidth = RightWidth;
topHeight = TopHeight;
bottomHeight = BottomHeight;
}
public void NoMargins()
{
leftWidth = 0;
rightWidth = 0;
topHeight = 0;
bottomHeight = 0;
}
public void SheetOfGlass()
{
leftWidth = -1;
rightWidth = -1;
topHeight = -1;
bottomHeight = -1;
}
}
[SuppressUnmanagedCodeSecurityAttribute]
internal static class SafeNativeMethods
{
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa969508(v=vs.85).aspx
[DllImport("dwmapi.dll")]
internal static extern int DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind);
//https://msdn.microsoft.com/it-it/library/windows/desktop/aa969512(v=vs.85).aspx
[DllImport("dwmapi.dll")]
internal static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa969515(v=vs.85).aspx
[DllImport("dwmapi.dll")]
internal static extern int DwmGetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize);
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa969524(v=vs.85).aspx
[DllImport("dwmapi.dll")]
internal static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize);
[DllImport("dwmapi.dll")]
internal static extern int DwmIsCompositionEnabled(ref int pfEnabled);
}
public static bool IsCompositionEnabled()
{
int pfEnabled = 0;
int result = SafeNativeMethods.DwmIsCompositionEnabled(ref pfEnabled);
return (pfEnabled == 1) ? true : false;
}
public static bool IsNonClientRenderingEnabled(IntPtr hWnd)
{
int gwaEnabled = 0;
int result = SafeNativeMethods.DwmGetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingEnabled, ref gwaEnabled, sizeof(int));
return (gwaEnabled == 1) ? true : false;
}
public static bool WindowSetAttribute(IntPtr hWnd, DWMWINDOWATTRIBUTE Attribute, int AttributeValue)
{
int result = SafeNativeMethods.DwmSetWindowAttribute(hWnd, Attribute, ref AttributeValue, sizeof(int));
return (result == 0);
}
public static bool WindowEnableBlurBehind(IntPtr hWnd)
{
//Create and populate the Blur Behind structure
DWM_BLURBEHIND Dwm_BB = new DWM_BLURBEHIND(true);
int result = SafeNativeMethods.DwmEnableBlurBehindWindow(hWnd, ref Dwm_BB);
return (result == 0);
}
public static bool WindowExtendIntoClientArea(IntPtr hWnd, WinApi.Dwm.MARGINS Margins)
{
// Extend frame on the bottom of client area
int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins);
return (result == 0);
}
public static bool WindowBorderlessDropShadow(IntPtr hWnd, int ShadowSize)
{
MARGINS Margins = new MARGINS(0, ShadowSize, 0, ShadowSize);
int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins);
return (result == 0);
}
public static bool WindowSheetOfGlass(IntPtr hWnd)
{
MARGINS Margins = new MARGINS();
Margins.SheetOfGlass();
//Margins set to All:-1 - Sheet Of Glass effect
int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins);
return (result == 0);
}
public static bool WindowDisableRendering(IntPtr hWnd)
{
DWMNCRENDERINGPOLICY NCRP = DWMNCRENDERINGPOLICY.Disabled;
int ncrp = (int)NCRP;
// Disable non-client area rendering on the window.
int result = SafeNativeMethods.DwmSetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingPolicy, ref ncrp, sizeof(int));
return (result == 0);
}
}
}
I set the bottomHeight to 3, and I found that the border height was included in the form size (the form's size didn't change).
So I set a BackgroundImage to this form, and the border was hidden by the image.
Related
I used:
myComboBox.DrawMode = DrawMode.OwnerDrawFixed;
Then I implemented the DrawItem event like so:
private void myComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0)
return;
string text = myComboBox.GetItemText(myComboBox.Items[e.Index]);
e.DrawBackground();
using var brush = new SolidBrush(e.ForeColor);
e.Graphics.DrawString(text, e.Font!, brush, e.Bounds);
if (myComboBox.DroppedDown && (e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
var item = (IndexedItem)myComboBox.Items[e.Index]; // IndexedItem is my own class to hold the index and name of a combobox item
if (!string.IsNullOrWhiteSpace(item.Name))
myToolTip.Show(item.Name, myComboBox, e.Bounds.Right, e.Bounds.Bottom);
}
e.DrawFocusRectangle();
}
The purpose is to show a tooltip for each item when I hover it. The above code works fine but sometimes the dropdown is shown above instead of below due to available space.
The problem now is, that DrawBackground etc use the adjusted positions but e.Bounds still contains the area below the control. So the dropdown is shown above but the tooltip below the combobox. I guess DrawBackground modifies the bounds internally but doesn't write the adjusted value back to e.Bounds. Now the question is, how can I determine the correct bounds of the item in that case?
Ok I managed to find the correct bounds via interops like this:
Rectangle GetItemBounds(int index)
{
const int SB_VERT = 0x1;
const int SIF_RANGE = 0x1;
const int SIF_POS = 0x4;
const uint GETCOMBOBOXINFO = 0x0164;
var info = new COMBOBOXINFO();
info.cbSize = Marshal.SizeOf(info);
SendMessageW(
myComboBox.Handle,
GETCOMBOBOXINFO,
IntPtr.Zero,
ref info);
GetWindowRect(info.hwndList, out RECT rc);
var dropdownArea = new Rectangle(myComboBox.PointToClient(rc.Location), rc.Size);
int yDiff = index * myComboBox.ItemHeight;
var scrollInfo = new SCROLLINFO();
scrollInfo.cbSize = (uint)Marshal.SizeOf(scrollInfo);
scrollInfo.fMask = SIF_RANGE | SIF_POS;
GetScrollInfo(info.hwndList, SB_VERT, ref scrollInfo);
int scrollY = scrollInfo.nPos * myComboBox.ItemHeight;
return new Rectangle(dropdownArea.X, dropdownArea.Y - scrollY + yDiff, rc.Width, myComboBox.ItemHeight);
}
And then use it like this:
var realBounds = GetItemBounds(e.Index);
I am not sure if this is the best approach but it even works with scrolling inside the dropdown now.
The interops look like this:
[StructLayout(LayoutKind.Sequential)]
struct COMBOBOXINFO
{
public Int32 cbSize;
public RECT rcItem, rcButton;
public int buttonState;
public IntPtr hwndCombo, hwndEdit, hwndList;
}
[Serializable, StructLayout(LayoutKind.Sequential)]
struct SCROLLINFO
{
public uint cbSize;
public uint fMask;
public int nMin;
public int nMax;
public uint nPage;
public int nPos;
public int nTrackPos;
}
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetScrollInfo(IntPtr hwnd, int fnBar, ref SCROLLINFO lpsi);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left, Top, Right, Bottom;
public RECT(int left, int top, int right, int bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public RECT(System.Drawing.Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom) { }
public int X
{
get { return Left; }
set { Right -= (Left - value); Left = value; }
}
public int Y
{
get { return Top; }
set { Bottom -= (Top - value); Top = value; }
}
public int Height
{
get { return Bottom - Top; }
set { Bottom = value + Top; }
}
public int Width
{
get { return Right - Left; }
set { Right = value + Left; }
}
public System.Drawing.Point Location
{
get { return new System.Drawing.Point(Left, Top); }
set { X = value.X; Y = value.Y; }
}
public System.Drawing.Size Size
{
get { return new System.Drawing.Size(Width, Height); }
set { Width = value.Width; Height = value.Height; }
}
public static implicit operator System.Drawing.Rectangle(RECT r)
{
return new System.Drawing.Rectangle(r.Left, r.Top, r.Width, r.Height);
}
public static implicit operator RECT(System.Drawing.Rectangle r)
{
return new RECT(r);
}
public static bool operator ==(RECT r1, RECT r2)
{
return r1.Equals(r2);
}
public static bool operator !=(RECT r1, RECT r2)
{
return !r1.Equals(r2);
}
public bool Equals(RECT r)
{
return r.Left == Left && r.Top == Top && r.Right == Right && r.Bottom == Bottom;
}
public override bool Equals(object? obj)
{
if (obj is RECT)
return Equals((RECT)obj);
else if (obj is System.Drawing.Rectangle)
return Equals(new RECT((System.Drawing.Rectangle)obj));
return false;
}
public override int GetHashCode()
{
return ((System.Drawing.Rectangle)this).GetHashCode();
}
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.CurrentCulture, "{{Left={0},Top={1},Right={2},Bottom={3}}}", Left, Top, Right, Bottom);
}
}
[DllImport("user32")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT rc);
[DllImport("user32", ExactSpelling = true)]
public static extern IntPtr SendMessageW(
IntPtr hWnd,
uint Msg,
IntPtr wParam = default,
IntPtr lParam = default);
public unsafe static IntPtr SendMessageW<T>(
IntPtr hWnd,
uint Msg,
IntPtr wParam,
ref T lParam) where T : unmanaged
{
fixed (void* l = &lParam)
{
return SendMessageW(hWnd, Msg, wParam, (IntPtr)l);
}
}
I created an extension:
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static class ComboBoxExtensions
{
public static Rectangle GetItemBounds(this ComboBox comboBox, int index)
{
const int SB_VERT = 0x1;
const int SIF_RANGE = 0x1;
const int SIF_POS = 0x4;
const uint GETCOMBOBOXINFO = 0x0164;
var info = new Interop.COMBOBOXINFO();
info.cbSize = Marshal.SizeOf(info);
Interop.SendMessageW(
comboBox.Handle,
GETCOMBOBOXINFO,
IntPtr.Zero,
ref info);
Interop.GetWindowRect(info.hwndList, out Interop.RECT rc);
var dropdownArea = new Rectangle(comboBox.PointToClient(rc.Location), rc.Size);
int yDiff = index * comboBox.ItemHeight;
var scrollInfo = new Interop.SCROLLINFO();
scrollInfo.cbSize = (uint)Marshal.SizeOf(scrollInfo);
scrollInfo.fMask = SIF_RANGE | SIF_POS;
Interop.GetScrollInfo(info.hwndList, SB_VERT, ref scrollInfo);
int scrollY = scrollInfo.nPos * comboBox.ItemHeight;
return new Rectangle(dropdownArea.X, dropdownArea.Y - scrollY + yDiff, rc.Width, comboBox.ItemHeight);
}
}
I realize you have already answered your own question. This is just plan B.
Your post mentions that the purpose is to show a tooltip for each item when I hover it so this answer focuses on that aspect. It doesn't make use of the item bounds info but that would be available in the DrawItem handler if you still need it.
This approach is loosely based on this answer and takes advantage of comboBox.SelectedItem property changing (but without firing an event) as the mouse moves over the dropped-down list. It uses that change to draw tool tips on an owner-draw combo box (only it doesn't have to be an owner-draw combo box for it to work).
This sample code for MainForm starts a timer when the ComboBox drops and ends it when it closes. It polls the SelectedIndex property on each tick.
public MainForm()
{
InitializeComponent();
// Works with or without owner draw.
// This line may be commented out
comboBox.DrawMode = DrawMode.OwnerDrawFixed;
// Add items
foreach (var item in Enum.GetValues(typeof(ComboBoxItems)))
comboBox.Items.Add(item);
// Start timer on drop down
comboBox.DropDown += (sender, e) => _toolTipTimer.Enabled = true;
// End timer on closed
comboBox.DropDownClosed += (sender, e) =>
{
_toolTipTimer.Enabled = false;
_lastToolTipIndex = -1;
_toolTip.Hide(comboBox);
};
// Poll index while open
_toolTipTimer.Tick += (sender, e) =>
{
if(comboBox.SelectedIndex != _lastToolTipIndex)
{
_lastToolTipIndex = comboBox.SelectedIndex;
showToolTip();
}
};
If there is a new index, the local method showToolTip is invoked to show the correct text.
void showToolTip()
{
if (_lastToolTipIndex != -1)
{
// Get the item
var item = (ComboBoxItems)comboBox.Items[_lastToolTipIndex];
// Get the tip
var tt = TipAttribute.FromMember(item);
// Get the rel pos
var mousePosition = PointToClient(MousePosition);
var rel = new Point(
(mousePosition.X - comboBox.Location.X) - 10,
(mousePosition.Y - comboBox.Location.Y) - 30);
// Show the tip
_toolTip.Show(tt, comboBox, rel);
}
}
}
private ToolTip _toolTip = new ToolTip();
private readonly Timer _toolTipTimer = new Timer() { Interval = 100 };
private int _lastToolTipIndex = -1;
The list items are represented by this enum:
enum ComboBoxItems
{
[Tip("...a day keeps the doctor away")]
Apple,
[Tip("...you glad I didn't say 'banana?'")]
Orange,
[Tip("...job on the Tool Tips!")]
Grape,
}
Where TipAttribute is defined as:
internal class TipAttribute : Attribute
{
public TipAttribute(string tip) => Tip = tip;
public string Tip { get; }
public static string FromMember(Enum value) =>
((TipAttribute)value
.GetType()
.GetMember($"{value}")
.Single()
.GetCustomAttribute(typeof(TipAttribute))).Tip;
}
I am creating a Speed Meter to measure my internet speed and stays at top of every app, then I how do I make Its background semi transparent or blurred something like this.
A WinForms Form with a Blur effect applied to it, using:
Windows 7 ⇒ DwmEnableBlurBehindWindow() DWM function.
Windows 10 / 11 ⇒ SetWindowCompositionAttribute() User32 function (undocumented)
How to apply the Blur Behind effect:
Windows 7:
The Window needs to register a rendering policy with DwmSetWindowAttribute(), setting the DWMWINDOWATTRIBUTE enumerator to NCRenderingPolicy and enable it, setting the DWMNCRENDERINGPOLICY enumerator to Enabled.
You may also want to override a Form's class WndProc; when a WM_DWMCOMPOSITIONCHANGED message is received (informing of the Aero composition state), to verify whether DWM Composition is enabled.
Before showing the Window interface, call DwmEnableBlurBehindWindow(), setting its DWM_BLURBEHIND structure relevant fields (dwFlags and fEnable) to 1.
Here, I'm calling it from the Form's constructor.
Windows 10 and Windows 11:
This code is using the not yet documented SetWindowCompositionAttribute() function.
The User32 function only requires the use of an internal structure, here called WinCompositionAttrData, where the Attribute member is set to DWMWINDOWATTRIBUTE.AccentPolicy and the Data member is set to the pointer of an internal structure, here called AccentPolicy, where the AccentState member is set to DWMACCENTSTATE.ACCENT_ENABLE_BLURBEHIND
DWM Compostion is always enabled. No need to verify it or override WndProc to handle a DWM Composition change.
It's more clear in code:
(As a note, the BlurBehind effect does not work if the Form has a white background color)
See this other question about a DwmExtendFrameIntoClientArea() implementation.
public partial class frmBlurBehind : Form
{
public frmBlurBehind()
{
InitializeComponent();
// Remove the border if this is meant to be a border-less Form
// FormBorderStyle = FormBorderStyle.None;
if (IsDWMCompositionEnabled()) {
if (Environment.OSVersion.Version.Major > 6) {
Dwm.Windows10EnableBlurBehind(Handle);
}
else {
Dwm.WindowEnableBlurBehind(Handle);
}
// Set Drop shadow of a border-less Form
if (FormBorderStyle == FormBorderStyle.None) {
Dwm.WindowBorderlessDropShadow(Handle, 2);
}
}
}
private bool IsDWMCompositionEnabled() =>
Environment.OSVersion.Version.Major >= 6 && Dwm.IsCompositionEnabled();
// Eventually, if this is a border-less Form, reapply the attribute if DWM Composition changes
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg) {
case Dwm.WM_DWMCOMPOSITIONCHANGED:
if (IsDWMCompositionEnabled()) {
Dwm.DWMNCRENDERINGPOLICY policy = Dwm.DWMNCRENDERINGPOLICY.Enabled;
Dwm.WindowSetAttribute(Handle, Dwm.DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)policy);
Dwm.WindowBorderlessDropShadow(Handle, 2);
m.Result = IntPtr.Zero;
}
break;
default:
break;
}
}
}
The Dwm class contain all interop functions and structures used above, plus a bunch of other methods that could become useful in this context
[SuppressUnmanagedCodeSecurity]
public class Dwm {
public const int WM_DWMCOMPOSITIONCHANGED = 0x031E;
public struct MARGINS {
public int leftWidth;
public int rightWidth;
public int topHeight;
public int bottomHeight;
public MARGINS(int LeftWidth, int RightWidth, int TopHeight, int BottomHeight)
{
leftWidth = LeftWidth;
rightWidth = RightWidth;
topHeight = TopHeight;
bottomHeight = BottomHeight;
}
public void NoMargins()
{
leftWidth = 0;
rightWidth = 0;
topHeight = 0;
bottomHeight = 0;
}
public void SheetOfGlass()
{
leftWidth = -1;
rightWidth = -1;
topHeight = -1;
bottomHeight = -1;
}
}
[Flags]
public enum DWM_BB {
Enable = 1,
BlurRegion = 2,
TransitionOnMaximized = 4
}
// https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
public enum DWMWINDOWATTRIBUTE : uint {
NCRenderingEnabled = 1, //Get atttribute
NCRenderingPolicy, //Enable or disable non-client rendering
TransitionsForceDisabled,
AllowNCPaint,
CaptionButtonBounds, //Get atttribute
NonClientRtlLayout,
ForceIconicRepresentation,
Flip3DPolicy,
ExtendedFrameBounds, //Get atttribute
HasIconicBitmap,
DisallowPeek,
ExcludedFromPeek,
Cloak,
Cloaked, //Get atttribute. Returns a DWMCLOACKEDREASON
FreezeRepresentation,
PassiveUpdateMode,
UseHostBackDropBrush,
AccentPolicy = 19, // Win 10 (undocumented)
ImmersiveDarkMode = 20, // Win 11 22000
WindowCornerPreference = 33, // Win 11 22000
BorderColor, // Win 11 22000
CaptionColor, // Win 11 22000
TextColor, // Win 11 22000
VisibleFrameBorderThickness, // Win 11 22000
SystemBackdropType // Win 11 22621
}
public enum DWMCLOACKEDREASON : uint {
DWM_CLOAKED_APP = 0x0000001, //cloaked by its owner application.
DWM_CLOAKED_SHELL = 0x0000002, //cloaked by the Shell.
DWM_CLOAKED_INHERITED = 0x0000004 //inherited from its owner window.
}
public enum DWMNCRENDERINGPOLICY : uint {
UseWindowStyle, // Enable/disable non-client rendering based on window style
Disabled, // Disabled non-client rendering; window style is ignored
Enabled, // Enabled non-client rendering; window style is ignored
};
public enum DWMACCENTSTATE {
ACCENT_DISABLED = 0,
ACCENT_ENABLE_GRADIENT = 1,
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
ACCENT_ENABLE_BLURBEHIND = 3,
ACCENT_INVALID_STATE = 4
}
[Flags]
public enum CompositionAction : uint {
DWM_EC_DISABLECOMPOSITION = 0,
DWM_EC_ENABLECOMPOSITION = 1
}
// Values designating how Flip3D treats a given window.
enum DWMFLIP3DWINDOWPOLICY : uint {
Default, // Hide or include the window in Flip3D based on window style and visibility.
ExcludeBelow, // Display the window under Flip3D and disabled.
ExcludeAbove, // Display the window above Flip3D and enabled.
};
public enum ThumbProperties_dwFlags : uint {
RectDestination = 0x00000001,
RectSource = 0x00000002,
Opacity = 0x00000004,
Visible = 0x00000008,
SourceClientAreaOnly = 0x00000010
}
[StructLayout(LayoutKind.Sequential)]
public struct AccentPolicy {
public DWMACCENTSTATE AccentState;
public int AccentFlags;
public int GradientColor;
public int AnimationId;
public AccentPolicy(DWMACCENTSTATE accentState, int accentFlags, int gradientColor, int animationId)
{
AccentState = accentState;
AccentFlags = accentFlags;
GradientColor = gradientColor;
AnimationId = animationId;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct DWM_BLURBEHIND {
public DWM_BB dwFlags;
public int fEnable;
public IntPtr hRgnBlur;
public int fTransitionOnMaximized;
public DWM_BLURBEHIND(bool enabled)
{
dwFlags = DWM_BB.Enable;
fEnable = (enabled) ? 1 : 0;
hRgnBlur = IntPtr.Zero;
fTransitionOnMaximized = 0;
}
public Region Region => Region.FromHrgn(hRgnBlur);
public bool TransitionOnMaximized {
get => fTransitionOnMaximized > 0;
set {
fTransitionOnMaximized = (value) ? 1 : 0;
dwFlags |= DWM_BB.TransitionOnMaximized;
}
}
public void SetRegion(Graphics graphics, Region region)
{
hRgnBlur = region.GetHrgn(graphics);
dwFlags |= DWM_BB.BlurRegion;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct WinCompositionAttrData {
public DWMWINDOWATTRIBUTE Attribute;
public IntPtr Data; //Will point to an AccentPolicy struct, where Attribute will be DWMWINDOWATTRIBUTE.AccentPolicy
public int SizeOfData;
public WinCompositionAttrData(DWMWINDOWATTRIBUTE attribute, IntPtr data, int sizeOfData)
{
Attribute = attribute;
Data = data;
SizeOfData = sizeOfData;
}
}
private static int GetBlurBehindPolicyAccentFlags()
{
int drawLeftBorder = 20;
int drawTopBorder = 40;
int drawRightBorder = 80;
int drawBottomBorder = 100;
return (drawLeftBorder | drawTopBorder | drawRightBorder | drawBottomBorder);
}
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa969508(v=vs.85).aspx
[DllImport("dwmapi.dll")]
internal static extern int DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind);
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern void DwmEnableComposition(CompositionAction uCompositionAction);
//https://msdn.microsoft.com/it-it/library/windows/desktop/aa969512(v=vs.85).aspx
[DllImport("dwmapi.dll")]
internal static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa969515(v=vs.85).aspx
[DllImport("dwmapi.dll")]
internal static extern int DwmGetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize);
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa969524(v=vs.85).aspx
[DllImport("dwmapi.dll")]
internal static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize);
[DllImport("User32.dll", SetLastError = true)]
internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WinCompositionAttrData data);
[DllImport("dwmapi.dll")]
internal static extern int DwmIsCompositionEnabled(ref int pfEnabled);
public static bool IsCompositionEnabled()
{
int pfEnabled = 0;
int result = DwmIsCompositionEnabled(ref pfEnabled);
return (pfEnabled == 1) ? true : false;
}
public static bool IsNonClientRenderingEnabled(IntPtr hWnd)
{
int gwaEnabled = 0;
int result = DwmGetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingEnabled, ref gwaEnabled, sizeof(int));
return gwaEnabled == 1;
}
public static bool WindowSetAttribute(IntPtr hWnd, DWMWINDOWATTRIBUTE attribute, int attributeValue)
{
int result = DwmSetWindowAttribute(hWnd, attribute, ref attributeValue, sizeof(int));
return (result == 0);
}
public static void Windows10EnableBlurBehind(IntPtr hWnd)
{
DWMNCRENDERINGPOLICY policy = DWMNCRENDERINGPOLICY.Enabled;
WindowSetAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)policy);
AccentPolicy accPolicy = new AccentPolicy() {
AccentState = DWMACCENTSTATE.ACCENT_ENABLE_BLURBEHIND,
};
int accentSize = Marshal.SizeOf(accPolicy);
IntPtr accentPtr = Marshal.AllocHGlobal(accentSize);
Marshal.StructureToPtr(accPolicy, accentPtr, false);
var data = new WinCompositionAttrData(DWMWINDOWATTRIBUTE.AccentPolicy, accentPtr, accentSize);
SetWindowCompositionAttribute(hWnd, ref data);
Marshal.FreeHGlobal(accentPtr);
}
public static bool WindowEnableBlurBehind(IntPtr hWnd)
{
DWMNCRENDERINGPOLICY policy = DWMNCRENDERINGPOLICY.Enabled;
WindowSetAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)policy);
DWM_BLURBEHIND dwm_BB = new DWM_BLURBEHIND(true);
int result = DwmEnableBlurBehindWindow(hWnd, ref dwm_BB);
return result == 0;
}
public static bool WindowExtendIntoClientArea(IntPtr hWnd, MARGINS margins)
{
// Extend frame on the bottom of client area
int result = DwmExtendFrameIntoClientArea(hWnd, ref margins);
return result == 0;
}
public static bool WindowBorderlessDropShadow(IntPtr hWnd, int shadowSize)
{
MARGINS margins = new MARGINS(0, shadowSize, 0, shadowSize);
int result = DwmExtendFrameIntoClientArea(hWnd, ref margins);
return result == 0;
}
public static bool WindowSheetOfGlass(IntPtr hWnd)
{
MARGINS margins = new MARGINS();
//Margins set to All:-1 - Sheet Of Glass effect
margins.SheetOfGlass();
int result = DwmExtendFrameIntoClientArea(hWnd, ref margins);
return result == 0;
}
public static bool WindowDisableRendering(IntPtr hWnd)
{
int ncrp = (int)DWMNCRENDERINGPOLICY.Disabled;
// Disable non-client area rendering on the window.
int result = DwmSetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingPolicy, ref ncrp, sizeof(int));
return result == 0;
}
} //DWM
This is a sample result with a Form.BackColor set to MidnightBlue:
Window Selected Windows Unselected
With some controls on it:
I want to write a WPF application that docks to an application running in another process (this is a 3rd party app I have no control of). Ideally I would like to be able to define if the app docks on the left or right.
Here's an example of what I want to do:
I have tried to implement the following 2 examples with no success.
Attach window to window of another process - Button_Click gives the following error:
Attach form window to another window in C# - Button_Click_1 docks it the title bar but I cannot see the entire app:
The following is the code:
namespace WpfApplicationTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
public static int GWL_STYLE = -16;
public static int WS_CHILD = 0x40000000;
[DllImport("user32")]
private static extern bool SetWindowPos(
IntPtr hWnd,
IntPtr hWndInsertAfter,
int x,
int y,
int cx,
int cy,
uint uFlags);
private IntPtr _handle;
private void SetBounds(int left, int top, int width, int height)
{
if (_handle == IntPtr.Zero)
_handle = new WindowInteropHelper(this).Handle;
SetWindowPos(_handle, IntPtr.Zero, left, top, width, height, 0);
}
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Process hostProcess = Process.GetProcessesByName("notepad").FirstOrDefault();
IntPtr hostHandle = hostProcess.MainWindowHandle;
//MyWindow window = new MyWindow();
this.ShowActivated = true;
HwndSourceParameters parameters = new HwndSourceParameters();
parameters.WindowStyle = 0x10000000 | 0x40000000;
parameters.SetPosition(0, 0);
parameters.SetSize((int)this.Width, (int)this.Height);
parameters.ParentWindow = hostHandle;
parameters.UsesPerPixelOpacity = true;
HwndSource src = new HwndSource(parameters);
src.CompositionTarget.BackgroundColor = Colors.Transparent;
src.RootVisual = (Visual)this.Content;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Process hostProcess = Process.GetProcessesByName("notepad").FirstOrDefault();
if (hostProcess != null)
{
Hide();
//this.WindowStyle;
//new WindowInteropHelper(this).SetBounds(0, 0, 0, 0, BoundsSpecified.Location);
//SetWindowPos(new WindowInteropHelper(this).Handle, IntPtr.Zero, 0, 0, 0, 0, 0);
SetBounds(0, 0, 0, 0);
IntPtr hostHandle = hostProcess.MainWindowHandle;
IntPtr guestHandle = new WindowInteropHelper(this).Handle;
SetWindowLong(guestHandle, GWL_STYLE, GetWindowLong(guestHandle, GWL_STYLE) | WS_CHILD);
SetParent(guestHandle, hostHandle);
Show();
}
}
}
You implementation is totally wrong, you are trying to make your window as a child window of the window you want to snap to.
I wrote a small helper class for snapping to another window by it's title, I hope this helps.
WindowSnapper.cs
public class WindowSnapper
{
private struct Rect
{
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
public int Height
{
get { return Bottom - Top; }
}
public static bool operator !=(Rect r1, Rect r2)
{
return !(r1 == r2);
}
public static bool operator ==(Rect r1, Rect r2)
{
return r1.Left == r2.Left && r1.Right == r2.Right && r1.Top == r2.Top && r1.Bottom == r2.Bottom;
}
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);
private DispatcherTimer _timer;
private IntPtr _windowHandle;
private Rect _lastBounds;
private Window _window;
private string _windowTitle;
public WindowSnapper(Window window, String windowTitle)
{
_window = window;
_window.Topmost = true;
_windowTitle = windowTitle;
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(10);
_timer.Tick += (x, y) => SnapToWindow();
_timer.IsEnabled = false;
}
public void Attach()
{
_windowHandle = GetWindowHandle(_windowTitle);
_timer.Start();
}
public void Detach()
{
_timer.Stop();
}
private void SnapToWindow()
{
var bounds = GetWindowBounds(_windowHandle);
if (bounds != _lastBounds)
{
_window.Top = bounds.Top;
_window.Left = bounds.Left - _window.Width;
_window.Height = bounds.Height;
_lastBounds = bounds;
}
}
private Rect GetWindowBounds(IntPtr handle)
{
Rect bounds = new Rect();
GetWindowRect(handle, ref bounds);
return bounds;
}
private IntPtr GetWindowHandle(string windowTitle)
{
foreach (Process pList in Process.GetProcesses())
{
if (pList.MainWindowTitle.Contains(windowTitle))
{
return pList.MainWindowHandle;
}
}
return IntPtr.Zero;
}
}
Usage example:
public partial class MainWindow : Window
{
private WindowSnapper _snapper;
public MainWindow()
{
InitializeComponent();
_snapper = new WindowSnapper(this, "Notepad");
_snapper.Attach();
}
}
I want every time you start my window form, he set at the bottom of the screen (above the taskbar)
public void goBottomWindow(Form targetForm)
{
targetForm.WindowState = FormWindowState.Maximized;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.TopMost = true;
WinApi.SetWinFullScreen(targetForm.Handle);
}
public class WinApi
{
[DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
public static extern int GetSystemMetrics(int which);
[DllImport("user32.dll")]
public static extern void
SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
int X, int Y, int width, int height, uint flags);
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private static IntPtr HWND_TOP = IntPtr.Zero;
private const int SWP_SHOWWINDOW = 64; // 0x0040
public static int ScreenX
{
get { return GetSystemMetrics(SM_CXSCREEN); }
}
public static int ScreenY
{
get {return 60;}
}
public static void SetWinFullScreen(IntPtr hwnd)
{
SetWindowPos(hwnd, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);
}
}
Using this code, it leaves my window form at the top of the screen .... but what I need is the form window positioned below.
It is possible to do this?
Sorry, my English is very bad :(
Why targetForm.WindowState = FormWindowState.Maximized; ?
isn't FormWindowState.Normal better for you?
Just fetch the dimension of your desktop/screen
var rect = Screen.PrimaryScreen.WorkingArea;
targetForm.Witdh = rect.Width;
targetForm.Top = rect.Height - targetForm.Height;
I saw that in your first lines it says targetForm.TopMost = true;
That means that your form will be TOPMOST, if you want your form to be BottomMost, you should change that to false;
Hope this helps! - CCB
Background:
I have a Forms.ComboBox with a DropDownStyle = DropDown.
I don't use AutoComplete, but I implemented something similar which does not only filter the beginning of the text, but uses a regular expression and shows all items which match the text entered. This works fine.
However, when I type the first letter of a matching item, the ComboBox falls back to its original behavior and sets DroppedDown = true and auto selects the first entry and completes the text to match the selected item (similar to AutoCompleteMode Append). What I want is no auto selection and auto completion.
What I found so far is, that I somehow have to prevent SendMessage() with CB_FINDSTRING of being called and replace CB_FINDSTRING with CB_FINDSTRINGEXACT (MSDN Link).
I think I have to extend the ComboBox class, but I'm not sure which methods I have to override. I'm working with C# .NET Framework v3.5.
Questions:
How do I extend a Windows.Forms.ComboBox to prevent the auto select behavior?
Links:
How can I prevent auto-select in ComboBox on drop-down except for exact matches? (did not help me)
Try this:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Opulos.Core.Win32;
namespace Opulos.Core.UI {
// Extension class to disable the auto-select behavior when a combobox is in DropDown mode.
public static class ComboBoxAutoSelectEx {
public static void AutoSelectOff(this ComboBox combo) {
Data.Register(combo);
}
public static void AutoSelectOn(this ComboBox combo) {
Data data = null;
if (Data.dict.TryGetValue(combo, out data)) {
data.Dispose();
Data.dict.Remove(combo);
}
}
private class Data {
// keep a reference to the native windows so they don't get disposed
internal static Dictionary<ComboBox, Data> dict = new Dictionary<ComboBox, Data>();
// a ComboBox consists of 3 windows (combobox handle, text edit handle and dropdown list handle)
ComboBox combo;
NW nwList = null; // handle to the combobox's dropdown list
NW2 nwEdit = null; // handle to the edit window
internal void Dispose() {
dict.Remove(this.combo);
this.nwList.ReleaseHandle();
this.nwEdit.ReleaseHandle();
}
public static void Register(ComboBox combo) {
if (dict.ContainsKey(combo))
return; // already registered
Data data = new Data() { combo = combo };
Action assign = () => {
if (dict.ContainsKey(combo))
return; // already assigned
COMBOBOXINFO info = COMBOBOXINFO.GetInfo(combo); // new COMBOBOXINFO();
//info.cbSize = Marshal.SizeOf(info);
//COMBOBOXINFO2.SendMessageCb(combo.Handle, 0x164, IntPtr.Zero, out info);
dict[combo] = data;
data.nwList = new NW(combo, info.hwndList);
data.nwEdit = new NW2(info.hwndEdit);
};
if (!combo.IsHandleCreated)
combo.HandleCreated += delegate { assign(); };
else
assign();
combo.HandleDestroyed += delegate {
data.Dispose();
};
}
}
private class NW : NativeWindow {
ComboBox combo;
public NW(ComboBox combo, IntPtr handle) {
this.combo = combo;
AssignHandle(handle);
}
private const int LB_FINDSTRING = 0x018F;
private const int LB_FINDSTRINGEXACT = 0x01A2;
protected override void WndProc(ref Message m) {
if (m.Msg == LB_FINDSTRING) {
m.Msg = LB_FINDSTRINGEXACT;
}
base.WndProc(ref m);
if (m.Msg == LB_FINDSTRINGEXACT) {
String find = Marshal.PtrToStringAuto(m.LParam);
for (int i = 0; i < combo.Items.Count; i++) {
Object item = combo.Items[i];
if (item.Equals(find)) {
m.Result = new IntPtr(i);
break;
}
}
}
}
}
private class NW2 : NativeWindow {
public NW2(IntPtr handle) {
AssignHandle(handle);
}
private const int EM_SETSEL = 0x00B1;
private const int EM_GETSEL = 0x00B0;
protected override void WndProc(ref Message m) {
if (m.Msg == EM_SETSEL) {
// if this code is not here, then the entire combobox text is selected
// which looks ugly, especially when there are multiple combo boxes.
//
// if this method returns immediately, then the caret position is set
// to (0, 0). However, it seems that calling EM_GETSEL has a side effect
// that the caret position is mostly maintained. Sometimes it slips back
// to (0, 0).
SendMessage(Handle, EM_GETSEL, IntPtr.Zero, IntPtr.Zero);
//int selStart = (sel & 0x00ff);
//int selEnd = (sel >> 16) & 0x00ff;
//Debug.WriteLine("EM_GETSEL: " + selStart + " nEnd: " + selEnd);
return;
}
base.WndProc(ref m);
}
[DllImportAttribute("user32.dll", SetLastError=true)]
private static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct COMBOBOXINFO {
public Int32 cbSize;
public RECT rcItem;
public RECT rcButton;
public int buttonState;
public IntPtr hwndCombo;
public IntPtr hwndEdit;
public IntPtr hwndList;
public static COMBOBOXINFO GetInfo(ComboBox combo) {
COMBOBOXINFO info = new COMBOBOXINFO();
info.cbSize = Marshal.SizeOf(info);
SendMessageCb(combo.Handle, 0x164, IntPtr.Zero, out info);
return info;
}
[DllImport("user32.dll", EntryPoint = "SendMessageW", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessageCb(IntPtr hWnd, int msg, IntPtr wp, out COMBOBOXINFO lp);
}
//[StructLayout(LayoutKind.Sequential)]
//public struct RECT {
// public int Left;
// public int Top;
// public int Right;
// public int Bottom;
//}
}