如何在透明窗口中绘制透明DirectX内容?
时间:2020-03-06 14:52:12 来源:igfitidea点击:
我想绘制DirectX内容,以使其看起来漂浮在桌面和正在运行的任何其他应用程序的上方。我还需要能够使DirectX内容半透明,这样其他东西才能显示出来。有没有办法做到这一点?
我在C#中使用Managed DX。
解决方案
我想如果不使用桌面窗口管理器,即要支持Windows XP,那将很难。使用DWM似乎很容易。
如果速度不是问题,则可以放弃渲染到表面,然后将渲染的图像复制到分层窗口。不过不要指望很快。
我从OregonGhost提供的链接开始,找到了一种适用于Vista的解决方案。这是Csyntax中的基本过程。此代码位于从Form继承的类中。如果在UserControl中,它似乎不起作用:
//this will allow you to import the necessary functions from the .dll using System.Runtime.InteropServices; //this imports the function used to extend the transparent window border. [DllImport("dwmapi.dll")] static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins); //this is used to specify the boundaries of the transparent area internal struct Margins { public int Left, Right, Top, Bottom; } private Margins marg; //Do this every time the form is resized. It causes the window to be made transparent. marg.Left = 0; marg.Top = 0; marg.Right = this.Width; marg.Bottom = this.Height; DwmExtendFrameIntoClientArea(this.Handle, ref marg); //This initializes the DirectX device. It needs to be done once. //The alpha channel in the backbuffer is critical. PresentParameters presentParameters = new PresentParameters(); presentParameters.Windowed = true; presentParameters.SwapEffect = SwapEffect.Discard; presentParameters.BackBufferFormat = Format.A8R8G8B8; Device device = new Device(0, DeviceType.Hardware, this.Handle, CreateFlags.HardwareVertexProcessing, presentParameters); //the OnPaint functions maked the background transparent by drawing black on it. //For whatever reason this results in transparency. protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; // black brush for Alpha transparency SolidBrush blackBrush = new SolidBrush(Color.Black); g.FillRectangle(blackBrush, 0, 0, Width, Height); blackBrush.Dispose(); //call your DirectX rendering function here } //this is the dx rendering function. The Argb clearing function is important, //as it makes the directx background transparent. protected void dxrendering() { device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 0, 0), 1.0f, 0); device.BeginScene(); //draw stuff here. device.EndScene(); device.Present(); }
最后,具有默认设置的窗体将具有玻璃状看起来部分透明的背景。将FormBorderStyle设置为" none",它将是100%透明的,只有内容浮在所有内容之上。
WPF也是另一种选择。
Developed by Microsoft, the Windows Presentation Foundation (or WPF) is a computer-software graphical subsystem for rendering user interfaces in Windows-based applications.