Форум программистов, компьютерный форум, киберфорум
DirectX
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.85/13: Рейтинг темы: голосов - 13, средняя оценка - 4.85
0 / 0 / 0
Регистрация: 02.04.2015
Сообщений: 4

SharpDx c#

03.04.2015, 12:49. Показов 2734. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Начал потихоньку изучать sharpdx
Пытался сделать оверлей, но никак не получается очистить экран без потери прозрачности окна
https://youtu.be/JdO8d9KJkJI
Собственно вопрос, как мне очистить экран так, что бы экран не становился черным?
Если надо, могу скинуть код
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
03.04.2015, 12:49
Ответы с готовыми решениями:

Уроки SharpDX
Где можно найти уроки/книги по SharpDX?

SharpDX не компилирует шейдеры
Здравствуйте, не знаю сюда ли это или в .Net ветку. В общем начал изучать SharpDX, до этого с голыми графическими апи не работал вообще,...

SharpDX: сохранение кадра в Bitmap
Доброго времени суток. Уже пару дней сижу, с казалось бы, простейшей задачей: взять front buffer и сунуть его в System.Drawing.Bitmap. ...

4
Эксперт С++
 Аватар для _lunar_
3701 / 2836 / 451
Регистрация: 03.05.2011
Сообщений: 5,193
Записей в блоге: 21
03.04.2015, 20:39
Цитата Сообщение от JumpAttacker Посмотреть сообщение
Если надо, могу скинуть код
покажите код. По другому помочь не смогу.
0
0 / 0 / 0
Регистрация: 02.04.2015
Сообщений: 4
03.04.2015, 20:51  [ТС]
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Windows.Forms;
using SharpDX;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using System.Diagnostics;
using System.Collections.Generic;
using D3D11 = SharpDX.Direct3D11;
using SharpDX.Direct2D1;
using SharpDX.DirectWrite;
using D2DFactory = SharpDX.Direct2D1.Factory;
using DWriteFactory = SharpDX.DirectWrite.Factory;
 
 
namespace sdx
{
    class Program
    {
        #region DllImport
        [DllImport("User32.dll")]
        static extern short GetAsyncKeyState(Int32 vKey);
        [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string lpClassName,
            string lpWindowName);
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
 
        [DllImport("user32.dll", SetLastError = true)]
 
        private static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);
        [DllImport("dwmapi.dll")]
        static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);
        [DllImport("user32.dll")]
        static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);//
 
        [DllImport("user32.dll")]
        #endregion
        #region Members
        static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);//
 
        public const int GWL_EXSTYLE = -20;
 
        public const int WS_EX_LAYERED = 0x80000;
 
        public const int WS_EX_TRANSPARENT = 0x20;
 
        public const int LWA_ALPHA = 0x2;
 
        public const int LWA_COLORKEY = 0x1;
        internal struct Margins
        {
            public int Left, Right, Top, Bottom;
        }
        
        
        private static Margins marg;
        private static RenderForm _renderForm;
 
        // General Direct3D 11 stuff
        private static SwapChain _swapChain;
        private static D3D11.Device _d3d11Device;
        private static DeviceContext _d3d11DevCon;
        private static WindowRenderTarget renderTarget;
 
        // Rainbow background colors
        private static SolidColorBrush backgroundBrush;
        private static SolidColorBrush redBrush;
 
        private static RectangleF textRegionRect;
        private static RectangleF fullTextBackground;
 
        private static D2DFactory d2dFactory;
        private static DWriteFactory dwFactory;
 
        #endregion
        static void Main(string[] args)
        {
            #region Init
            _renderForm = new RenderForm("Hax");
            _renderForm.StartPosition = FormStartPosition.CenterScreen;
            _renderForm.TopMost = true;
            _renderForm.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            _renderForm.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            _renderForm.BackColor = System.Drawing.Color.Black;
            _renderForm.ClientSize = new System.Drawing.Size(284, 262);
            _renderForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            _renderForm.ShowIcon = false;
            _renderForm.ShowInTaskbar = false;
            _renderForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
 
            d2dFactory = new D2DFactory();
            dwFactory = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            
            
            CreateResources(); 
            SetWindowLong(_renderForm.Handle, GWL_EXSTYLE,
                    (IntPtr)(GetWindowLong(_renderForm.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT));
 
            SetLayeredWindowAttributes(_renderForm.Handle, 0, 255, LWA_ALPHA);
            InitializeD3D11();
            var c = 100.0f;
            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() 
                { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(200, 500, 300, 300) });
            var solidColorBrush = new SolidColorBrush(renderTarget, Color.Gold);
            #endregion
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            RenderLoop.Run(_renderForm, () =>
            {
                renderTarget.BeginDraw();
                //renderTarget.Clear(new Color4(0,0,0,0));
                //renderTarget.FillRectangle(textRegionRect, redBrush);
                //renderTarget.FillRectangle(fullTextBackground, backgroundBrush);
                //solidColorBrush.Color = new Color4(200, 200, 200, (float)Math.Abs(Math.Cos(stopwatch.ElapsedMilliseconds * .001)));
                c += 0.01f;
                rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() 
                    { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(c, c+200, 300, 300) });
                renderTarget.FillGeometry(rectangleGeometry, redBrush, null);
                try
                {
                    renderTarget.EndDraw();
                }
                catch
                {
                    CreateResources();
                }
            });
            #region Dispose
            d2dFactory.Dispose();
            dwFactory.Dispose();
            renderTarget.Dispose();
            solidColorBrush.Dispose();
            rectangleGeometry.Dispose();
            #endregion
        }
        private static void InitializeD3D11()
        {
            ModeDescription bufferDescription = new ModeDescription()
            {
                Width = 0,
                Height = 0,
                RefreshRate = new Rational(60, 1),
                Format = Format.R8G8B8A8_UNorm
            };
            SwapChainDescription swapChainDescription = new SwapChainDescription()
            {
                ModeDescription = bufferDescription,
                SampleDescription = new SampleDescription(1, 0),
                Usage = Usage.RenderTargetOutput,
                BufferCount = 1,
                OutputHandle = _renderForm.Handle,
                IsWindowed = true
            };
            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None,
                swapChainDescription, out _d3d11Device, out _swapChain);
            _d3d11DevCon = _d3d11Device.ImmediateContext;
            marg.Left = 0;
            marg.Top = 0;
            marg.Right = _renderForm.Width;
            marg.Bottom = _renderForm.Height;
            DwmExtendFrameIntoClientArea(_renderForm.Handle, ref marg);
        }
 
 
        private static void CreateResources()
        {
            if (renderTarget != null) { renderTarget.Dispose(); }
            if (redBrush != null) { redBrush.Dispose(); }
            if (backgroundBrush != null) { backgroundBrush.Dispose(); }
            HwndRenderTargetProperties wtp = new HwndRenderTargetProperties();
            wtp.Hwnd = _renderForm.Handle;
            wtp.PixelSize = new Size2(_renderForm.ClientSize.Width, _renderForm.ClientSize.Height);
            wtp.PresentOptions = PresentOptions.Immediately;
            renderTarget = new WindowRenderTarget(d2dFactory, new RenderTargetProperties(), wtp);
            redBrush = new SolidColorBrush(renderTarget, Color.Red);
            textRegionRect = new RectangleF(10, 10, 300, 300);
            backgroundBrush = new SolidColorBrush(renderTarget, new Color4(0.0f, 50.0f, 255, 255.0f));
            fullTextBackground = new RectangleF(300, 300, 300, 300);
 
        }
    }
}
0
Эксперт С++
 Аватар для _lunar_
3701 / 2836 / 451
Регистрация: 03.05.2011
Сообщений: 5,193
Записей в блоге: 21
04.04.2015, 10:40
попробуйте так
C#
1
2
3
4
5
6
7
8
9
10
11
static void Main(string[] args)
{
    #region Init
    SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
    ...
    try
    {
        renderTarget.EndDraw();
        Invalidate();
    }
}
0
0 / 0 / 0
Регистрация: 02.04.2015
Сообщений: 4
04.04.2015, 12:35  [ТС]
Пришлось поменять RenderForm на Form и переписать немного остальное
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Windows.Forms;
using SharpDX;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using System.Diagnostics;
using System.Collections.Generic;
using D3D11 = SharpDX.Direct3D11;
using SharpDX.Direct2D1;
using SharpDX.DirectWrite;
using D2DFactory = SharpDX.Direct2D1.Factory;
using DWriteFactory = SharpDX.DirectWrite.Factory;
 
namespace SharpDx
{
    public partial class NewForm : Form
    {
        #region DllImport
        [DllImport("User32.dll")]
        static extern short GetAsyncKeyState(Int32 vKey);
        [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string lpClassName,
            string lpWindowName);
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
 
        [DllImport("user32.dll", SetLastError = true)]
 
        private static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);
        [DllImport("dwmapi.dll")]
        static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);
        [DllImport("user32.dll")]
        static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);//
 
        [DllImport("user32.dll")]
        #endregion
        #region Members
        static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);//
 
        public const int GWL_EXSTYLE = -20;
 
        public const int WS_EX_LAYERED = 0x80000;
 
        public const int WS_EX_TRANSPARENT = 0x20;
 
        public const int LWA_ALPHA = 0x2;
 
        public const int LWA_COLORKEY = 0x1;
        internal struct Margins
        {
            public int Left, Right, Top, Bottom;
        }
 
 
        private static Margins marg;
        //private static Form _renderForm;
 
        // General Direct3D 11 stuff
        private static SwapChain _swapChain;
        private static D3D11.Device _d3d11Device;
        private static DeviceContext _d3d11DevCon;
        private static WindowRenderTarget renderTarget;
 
        // Rainbow background colors
        private static SolidColorBrush backgroundBrush;
        private static SolidColorBrush redBrush;
 
        private static RectangleF textRegionRect;
        private static RectangleF fullTextBackground;
 
        private static D2DFactory d2dFactory;
        private static DWriteFactory dwFactory;
 
        #endregion
        public NewForm()
        {
            InitializeComponent();
 
            #region Init
            //this = this.FindForm();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.TopMost = true;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.Black;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
 
            d2dFactory = new D2DFactory();
            dwFactory = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
 
            CreateResources();
            SetWindowLong(this.Handle, GWL_EXSTYLE,
                    (IntPtr)(GetWindowLong(this.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT));
 
            SetLayeredWindowAttributes(this.Handle, 0, 255, LWA_ALPHA);
            InitializeD3D11();
            var c = 100.0f;
            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(200, 500, 300, 300) });
            var solidColorBrush = new SolidColorBrush(renderTarget, Color.Gold);
            #endregion
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            RenderLoop.Run(this, () =>
            {
                renderTarget.BeginDraw();
                //renderTarget.Clear(new Color4(0,0,0,0));
                //renderTarget.FillRectangle(textRegionRect, redBrush);
                //renderTarget.FillRectangle(fullTextBackground, backgroundBrush);
                //solidColorBrush.Color = new Color4(200, 200, 200, (float)Math.Abs(Math.Cos(stopwatch.ElapsedMilliseconds * .001)));
                c += 0.01f;
                rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(c, c + 200, 300, 300) });
                renderTarget.FillGeometry(rectangleGeometry, redBrush, null);
 
                try
                {
                    renderTarget.EndDraw();
                    this.Invalidate();
                }
                catch
                {
                    CreateResources();
                }
            });
            #region Dispose
            d2dFactory.Dispose();
            dwFactory.Dispose();
            renderTarget.Dispose();
            solidColorBrush.Dispose();
            rectangleGeometry.Dispose();
            #endregion
        }
        private void InitializeD3D11()
        {
            ModeDescription bufferDescription = new ModeDescription()
            {
                Width = 0,
                Height = 0,
                RefreshRate = new Rational(60, 1),
                Format = Format.R8G8B8A8_UNorm
            };
            SwapChainDescription swapChainDescription = new SwapChainDescription()
            {
                ModeDescription = bufferDescription,
                SampleDescription = new SampleDescription(1, 0),
                Usage = Usage.RenderTargetOutput,
                BufferCount = 1,
                OutputHandle = this.Handle,
                IsWindowed = true
            };
            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None,
                swapChainDescription, out _d3d11Device, out _swapChain);
            _d3d11DevCon = _d3d11Device.ImmediateContext;
            marg.Left = 0;
            marg.Top = 0;
            marg.Right = this.Width;
            marg.Bottom = this.Height;
            DwmExtendFrameIntoClientArea(this.Handle, ref marg);
        }
        private void CreateResources()
        {
            if (renderTarget != null) { renderTarget.Dispose(); }
            if (redBrush != null) { redBrush.Dispose(); }
            if (backgroundBrush != null) { backgroundBrush.Dispose(); }
            HwndRenderTargetProperties wtp = new HwndRenderTargetProperties();
            wtp.Hwnd = this.Handle;
            wtp.PixelSize = new Size2(this.ClientSize.Width, this.ClientSize.Height);
            wtp.PresentOptions = PresentOptions.Immediately;
            renderTarget = new WindowRenderTarget(d2dFactory, new RenderTargetProperties(), wtp);
            redBrush = new SolidColorBrush(renderTarget, Color.Red);
            textRegionRect = new RectangleF(10, 10, 300, 300);
            backgroundBrush = new SolidColorBrush(renderTarget, new Color4(0.0f, 50.0f, 255, 255.0f));
            fullTextBackground = new RectangleF(300, 300, 300, 300);
 
        }
    }
}

Но в итоге ничего не поменялось
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
04.04.2015, 12:35
Помогаю со студенческими работами здесь

SharpDX: одновременное выделение объектов
Здравствуйте! В проекте c SharpDX при наведении на два перекрывающие друг друга объекта происходит выделение сразу двух (скрин.1)....

Отрисовка Gizmos в RayTracer (SharpDX-ComputeShaders)
Добрый вечер, такая задача: необходимо отрисовывать Gizmos в рейтрейсере, который реализован на DirectX (враппер SharpDX) на...

SharpDX: ошибка при использовании swapChain.ResizeBuffers()
Здравствуйте! А проекте c SharpDX при изменении размера окна возникает ошибка в работе метода swapChain.ResizeBuffers(): HRESULT: , Module:...

Падение SharpDX
Привет всем! Версия SharpDX 2.5.0, обновиться пока не могу, ибо много кода придется переделывать (как оказалось, очень плохо у 3 версии с...

Документация по SharpDX
Доброго времени суток уважаемые товарищи! Решил я заняться графикой, погуглил и понял что лучше всего SharpDX, но документации по нему...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это дополнительная запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru