Quantcast
Channel: VBForums - CodeBank - Visual Basic .NET
Viewing all 525 articles
Browse latest View live

[THEME] Unique Theme GDI+ 14 Controls VB.Net

$
0
0
Unique Theme GDI+ - My Forth Theme (First shared here... ;) )


Inspiration & Credit to all Theme Creators of the HF


Control List -

1) Theme Container (with Blinking caption)
2) Unique Button
3) Unique Check Box
4) Unique Combo Box
5) Unique Control Box (Minimize & Maximize buttons can be disabled)
6) Unique Group Box
7) Unique Label (Show/Hide Border)
8) Unique Panel
9) Unique Progress Bar (Show/Hide Percentage Value), (with Blinking Bar)
10) Uniqe Radio Button
11) Unique Separator (with Horizontal & Vertical Alignment), (with Optional Text when Horizontal)
12) Unique Tab Control
13) Unique Text Box (Multiline support)
14) Unique Toggle


Screenshot -




Download -

http://pastebin.com/7yP3YPcQ


Note -

1) This is my Forth Theme... written while learning so it may have bugs...

2) Theme is coded without Themebase...

3) Constructive Criticism & Suggestions are always welcome...

4) Please leave comments for encouragement... ;)

5) Will add more controls if you find it useful & need arises... ;)

6) Credits to "Aeonhack" for Roundrect function...

7) Theme container idea taken from Mephobia's Perplex Theme


Regards
Saket

[RESOLVED] Show user: is my WinForm Foreground, and their Cursor over it?

$
0
0
For a specific application where I hide the window on timeout, I wanted to see if the user is resting his cursor over my window, eg reading. That's when it's foreground, so not overlapped, and the cursor within my window's rectangle.

MouseMove etc were insufficient with many controls etc.
I wasted a whole morning, until I found krakatou's post
- THANK YOU!

I now share back:
Code:

Function IsCursorOverMe() As Boolean
        Return CInt(Me.Handle) = GetForeGrWinAPI _
          And IsCursorOverMeWin()
    End Function

    Dim cursPoint As New Point
    Dim winRect As New Rectangle
    Function IsCursorOverMeWin() As Boolean
        GetCursorPosAPI(lpPoint)
        cursPoint.X = lpPoint.x
        cursPoint.Y = lpPoint.y
        winRect.Location = Me.Location
        winRect.Size = Me.Size
        Return winRect.Contains(cursPoint)
    End Function

Great forum, bye.

Color Contrast

$
0
0
I ran across a question about selecting the text color of a control based upon the background color. With some research I found three different methods. They are:

Code:

    Public Function GetContrastColor1(ctrl As Control) As Color
        '50%

        Dim c As Color = ctrl.BackColor
        Dim rv As Color

        Const threshold As Integer = &HFFFFFF \ 2

        If (c.ToArgb And &HFFFFFF) < threshold Then
            rv = Color.White
        Else
            rv = Color.Black
        End If
        Return rv
    End Function

    Public Function GetContrastColor2(ctrl As Control) As Color
        'inverted BackColor

        Dim c As Color = ctrl.BackColor
        Dim rv As Color

        Dim R As Integer = Not c.R
        Dim G As Integer = Not c.G
        Dim B As Integer = Not c.B

        rv = Color.FromArgb(ctrl.BackColor.A, R, G, B)

        Return rv
    End Function

    Public Function GetContrastColor3(ctrl As Control) As Color
        'YIQ

        Dim c As Color = ctrl.BackColor
        Dim rv As Color

        Dim R As Integer = c.R
        Dim G As Integer = c.G
        Dim B As Integer = c.B

        Dim yiq As Integer = ((R * 299) + (G * 587) + (B * 114)) \ 1000

        rv = If(yiq >= 128, Color.Black, Color.White)

        Return rv
    End Function

Overall the YIQ method seems to produce the best results.

Number to Words

$
0
0
Converts longs > Long.MinValue to words. The code uses recursion FWIW.

Code:

Public Class NumberToWords

    ''' <summary>
    ''' Convert any Long (except Long.MinValue) to words
    ''' </summary>
    ''' <param name="someNum">the number to be converted</param>
    ''' <param name="negativePrefix">the prefix to use if the number is negative</param>
    ''' <returns>string representation of number</returns>
    ''' <remarks>won't convert Long.MinValue</remarks>
    Public Shared Function Convert(someNum As Long, Optional negativePrefix As String = "negative") As String
        'convert using NumToString
        Return NumToString(someNum, 0, negativePrefix)
    End Function

    Private Shared Function NumToString(num As Long, level As Integer, Optional negativeprfx As String = "") As String
        'on entry level represents the recursive depth
        'Debug.Write(level & " ")

        Dim rv As New System.Text.StringBuilder
        Dim workingNum As Long = num 'working number

        Const appender As String = ", "
        Const entyAppender As String = "-" 'for hyphens on the 'entys 20, 30, 40, etc

        'for this to work the number must be positive
        'and greater than Long.MinValue
        If workingNum = Long.MinValue Then
            Throw New ArgumentException("Can't convert Long.MinValue")
        End If
        'the negative, if any is
        'fixed at the end
        Dim isNeg As Boolean = False
        If workingNum < 0L Then
            isNeg = True
            workingNum = -workingNum 'convert to positive if needed
            'or
            'old school
            'reverse the bits and add one
            'workingNum = workingNum Xor &HFFFFFFFFFFFFFFFFL
            'workingNum += 1L
        End If

        'is the number known?
        rv.Append(Defined(workingNum))
        If rv.Length = 0 Then 'known?
            'no
            'the groups defined as long
            'so that the results don't have to be converted
            Dim ones As Long = 0L
            Dim tens As Long = 0L
            Dim hundreds As Long = 0L
            Dim thousands As Long = 0L
            Dim millions As Long = 0L
            Dim billions As Long = 0L
            Dim trillions As Long = 0L
            Dim quadrillions As Long = 0L
            Dim quintillions As Long = 0L

            'get count of each grouping
            'decreasing workingNum by the grouping total

            'only during the first call to this method
            'can the number be > 999
            If level = 0 Then
                quintillions = workingNum \ NumWords.quintillion
                workingNum -= quintillions * NumWords.quintillion

                quadrillions = workingNum \ NumWords.quadrillion
                workingNum -= quadrillions * NumWords.quadrillion

                trillions = workingNum \ NumWords.trillion
                workingNum -= trillions * NumWords.trillion

                billions = workingNum \ NumWords.billion
                workingNum -= billions * NumWords.billion

                millions = workingNum \ NumWords.million
                workingNum -= millions * NumWords.million

                thousands = workingNum \ NumWords.thousand
                workingNum -= thousands * NumWords.thousand

                'now check each group
                'and recursively call
                'on the groups amount which will be < 1000
                If quintillions > 0L Then
                    rv.Append(NumToString(quintillions, level + 1))
                    rv.Append(" ")
                    rv.Append(NumWords.quintillion.ToString)
                    rv.Append(appender)
                End If

                If quadrillions > 0L Then
                    rv.Append(NumToString(quadrillions, level + 1))
                    rv.Append(" ")
                    rv.Append(NumWords.quadrillion.ToString)
                    rv.Append(appender)
                End If

                If trillions > 0L Then
                    rv.Append(NumToString(trillions, level + 1))
                    rv.Append(" ")
                    rv.Append(NumWords.trillion.ToString)
                    rv.Append(appender)
                End If

                If billions > 0L Then
                    rv.Append(NumToString(billions, level + 1))
                    rv.Append(" ")
                    rv.Append(NumWords.billion.ToString)
                    rv.Append(appender)
                End If

                If millions > 0L Then
                    rv.Append(NumToString(millions, level + 1))
                    rv.Append(" ")
                    rv.Append(NumWords.million.ToString)
                    rv.Append(appender)
                End If

                If thousands > 0L Then
                    rv.Append(NumToString(thousands, level + 1))
                    rv.Append(" ")
                    rv.Append(NumWords.thousand.ToString)
                    rv.Append(appender)
                End If
            End If

            hundreds = workingNum \ NumWords.hundred
            workingNum -= hundreds * NumWords.hundred

            'special case for tens
            'if the number is less than 20
            'don't bother dividing by ten
            'because all numbers less than 20 are defined
            'note: 20 is known but should be treated as a ten

            If workingNum > 19L Then
                tens = workingNum \ NumWords.ten
                workingNum -= tens * NumWords.ten
            End If

            ones = workingNum 'what is left

            If hundreds > 0L Then
                rv.Append(NumToString(hundreds, level + 1))
                rv.Append(" ")
                rv.Append(NumWords.hundred.ToString)
                rv.Append(" ")
            End If

            If tens > 0L Then
                'the tens (10, 20, 30 ...) are defined
                rv.Append(NumToString(tens * NumWords.ten, level + 1)) ' times ten to get the defined number string
                rv.Append(entyAppender)
            End If

            If ones > 0 Then
                rv.Append(NumToString(ones, level + 1))
                rv.Append(" ")
            End If
        End If

        'known numbers come directly here

        'was the number negative?
        If isNeg Then
            If negativeprfx.Length <> 1 Then
                rv.Insert(0, " ")
                rv.Insert(0, negativeprfx)
            Else
                rv.Insert(0, negativeprfx)
            End If
        End If
        'get rid of trailing spaces and hyphens, if any
        Return rv.ToString.TrimEnd(appender.ToCharArray).TrimEnd(entyAppender.ToCharArray)
    End Function

    Private Shared Function Defined(num As Long) As String
        'is the number defined and less than 100
        If [Enum].IsDefined(GetType(NumWords), num) AndAlso num < 100L Then
            'yes
            Return [Enum].GetName(GetType(NumWords), num)
        Else
            'no
            Return ""
        End If
    End Function

    Enum NumWords As Long
        zero = 0L
        one = 1L
        two = 2L
        three = 3L
        four = 4L
        five = 5L
        six = 6L
        seven = 7L
        eight = 8L
        nine = 9L
        ten = 10L
        eleven = 11L
        twelve = 12L
        thirteen = 13L
        fourteen = 14L
        fifteen = 15L
        sixteen = 16L
        seventeen = 17L
        eightteen = 18L
        nineteen = 19L
        twenty = 20L
        thirty = 30L
        forty = 40L
        fifty = 50L
        sixty = 60L
        seventy = 70L
        eighty = 80L
        ninety = 90L
        hundred = 100L
        thousand = 1000L
        million = 1000000L
        billion = 1000000000L
        trillion = 1000000000000L
        quadrillion = 1000000000000000L
        quintillion = 1000000000000000000L
    End Enum
End Class

Making a Combobox Ready Only

$
0
0
Hi,

I have read numerous suggestions on how to make a combobox readonly in vb.net/C#. Please bear in mind that the ReadOnly Property is only available for texboxes. The reason for this is two-fold: 1. to make the data more readable 2. allow the user to copy the data. But when it comes to Combobox... you either disable it (Readability is poor) or change the DropDownStyle to DropDownList (Really standards out on the from).

I use to create a combobox and a textbook, if the user is entering data... I set the combobox visible and the textbox not visible. When the user is enquiry on the data, I set the textbox visible, set the readyonly to true and set the tabstop to false, and make the combobox not visible... mission accomplished and it works great.

I've seen a solution where the developer wants to avoid placing a textbook and a combobox on the form, and instead... draws his/her own textbox at runtime, then making either the combobox visible or the self drawn textbox depending on the requirement. Da... this is the same this as place a textbox on the form and making it not visible... extra and unnecessary coding. Last night I played around with comboboxes, and then came up with a different solutions, I think it is cool and it accomplishes what the textbox offers when in readonly mode... See below:

NB! I only create one combobox and not an additional textbox control.
If the user is entering data then
set the dropdownstyle to dropdown (combobox.DropDownStyle = DropDownStyle.DropDown)

If the user is enquiring on data then
assign combobox.text to a User define variable (strStore)
set the dropdownstyle to simple (combobox.DropDownStyle = DropDownStyle.Simple)
set the tabstop to false (combobox.TabStop = False)

This will allow the user to see the combobox as a textbox (Readability) and Copy the data in the combobox, accomplishing the same result as with a textbox in readonly mode. The user is unable to tab to the combobox, but can click on the combobox to highlight the data for copying purposes.

Mission still not accomplished... You will always get a user who will try to break the system! If I user established that he/she can still overwrite the data in the combobox, you may have a problem, depending how you have design your program. But to make sure that no data is changed... add the following:

On the combobox Leave event
Assign the User defined variable (strStore) to the combobox.text. This will ensure that no data is changed.

Hope this makes sense..

Motion Detector.NET - detects movement inside a webcam's field of view.

$
0
0
This program captures images from a webcam and determines the level of movement in the camera's field of view. When the level of movement exceeds a threshold specified by the user, it displays a message box.

The program works by comparing the most recently captured image with the previous one. The difference between the two images is used to determine the level of movement. Thanks to the LockBits/UnlockBits methods the GetPixel/SetPixel functions/methods are avoided which improves the program's performance.

This program should also be useful to find out how to use a webcam in general in Visual Basic.NET.

See the attached .zip file for the program.

This program is a .NET version of: Motion Viewer (Vb 6)
It does not (yet?) have an e-mail function though.
Attached Files

Check if URL Exists Function :)

$
0
0
vb.net Code:
  1. 'Button Click Event
  2.  
  3.  If CheckURL(TextBoxX1.Text) = True Then
  4.                 wb1.Navigate(TextBoxX1.Text)
  5.             Else
  6.                 MessageBox.Show("The following URL: " & TextBoxX1.Text & " is incorrect, please try again using a correct URL!", "Invalid URL", MessageBoxButtons.OK, MessageBoxIcon.Error)
  7.             End If


vb.net Code:
  1. Public Function CheckURL(ByVal urltocheck As String)
  2.         Dim url As New System.Uri("http://" & urltocheck)
  3.         Dim req As System.Net.WebRequest
  4.         req = System.Net.WebRequest.Create(url)
  5.         Dim resp As System.Net.WebResponse
  6.         Try
  7.             resp = req.GetResponse()
  8.             resp.Close()
  9.             req = Nothing
  10.             Return True
  11.         Catch ex As Exception
  12.             req = Nothing
  13.             Return False
  14.         End Try
  15.     End Function

Simple Image Resize Function

$
0
0
vb.net Code:
  1. Public Shared Function ResizeImage(ByVal InputImage As Image, ByVal NewWidth As Integer, ByVal NewHeight As Integer) As Image
  2.         Return New Bitmap(InputImage, New Size(NewWidth, NewHeight))
  3. End Function

Use it like this:

vb.net Code:
  1. ResizeImage(YourImage, Width, Height)

DropDown Combo w/Search Button

$
0
0
A DropDown (only) style ComboBox with a built-in search button.

1) Add ComboEz.vb and ComboEz.resx to a project as existing item.
2) Build.
3) Add control from toolbox to form.

Clicking the search image or calling PerformClick of combo will raise the combo's ClickSearch event.

Created with VB10/FW 4.0.

Name:  ComboBoxButton.png
Views: 97
Size:  14.8 KB
Attached Images
 
Attached Files

[CLASS] Save List of Images to My.Settings! (Made by: TnTinMN)

$
0
0
Make a new class and replace all the text in it with this text:

vb.net Code:
  1. Namespace My
  2.     Partial Friend NotInheritable Class MySettings
  3.                  <Global.System.Configuration.SettingsSerializeAs(Configuration.SettingsSerializeAs.Binary)> _
  4.         <Global.System.Configuration.UserScopedSettingAttribute()> _
  5.         Public Property ImageList() As List(Of System.Drawing.Image)
  6.             Get
  7.                 ' the String in: Me("ImageList") must be the name of the setting
  8.                 If Me("ImageList") Is Nothing Then
  9.                     Me("ImageList") = New List(Of System.Drawing.Image)
  10.                 End If
  11.                 Return DirectCast(Me("ImageList"), List(Of System.Drawing.Image))
  12.             End Get
  13.             Set(ByVal value As List(Of System.Drawing.Image))
  14.                 ' the String in: Me("UserImages") must be the name of the setting
  15.                 Me("ImageList") = value
  16.             End Set
  17.         End Property
  18.     End Class
  19. End Namespace

Example how to add Images to
vb.net Code:
  1. My.MySettings.Default.ImageList

On button click event you can do something like this:

vb.net Code:
  1. For Each pic As PictureBox In Me.Controls
  2.      My.MySettings.Default.ImageList.Add(pic.Image)
  3.      My.MySettings.Default.Save()
  4. Next

WebBrowser Control behavior similar to Internet Explorer

$
0
0
Recently,

I was asked if the .NET Winforms WebBrowser control can emulate the behaviour of Internet Explorer like rendering of images from a website. After doing some research, I found a solution here which is in C#: c-sharp-webbrowser-ajax-call and MSDN browser emulation reference: MSDN browser_emulation

Since the previous versions of programs using the webbrowser control were developed in VB.NET, I decided to apply it in VB.NET. The functions are defined in BrowserFeature class. And to use it, just create an object on the form's constructor and then call the SetBrowserFeatureControl() method.

Note:
- The executable files are deployed on dedicated servers (Only OS and .NET framework installed. No software applications)
- Backup registry before deploying the executable files.
- Tested OS: Windows 7, 8, 8.1
- IE Browser: 10, 11

- KGC

Source Code: VS 2012
Attached Files

Create MS-Access database at run time with several options

$
0
0
This article demonstrates (VS2012 solution is here) in a VB.NET solution how to create a MS-Access 2007 database using Office automation and OleDb data provider to create a single table in the newly created MS-Access 2007 database.

There are two trains of thoughts in regard to providing a new database then creating one or more tables. The first is what I would recommend which is, create a folder beneath the application folder and place a blank database there. When the application requires a new database copy the blank database to the location (in this case the application folder) where you need the blank database then create the tables as needed. Using this method there is no need to use Office automation or a archaic version to create a database via ADOX which we mainly will get an MDB not a ACCDB and may not work in newer versions of the Windows operation system. The second method is to use Office automation to generate the database then continue with creation of tables.

Addendum to the above, using the copy method the blank database could already have predefined tables already thus no need to create tables.

If you need to create tables no matter how the database was created we can use OleDb data provider with SQL to create our tables but cannot create relationships this way. To create relationships we need to get back into Office automation or DAO (which again is a risk depending on the Windows OS).

In the sample solution there are two projects. One is a class project which is responsible for creating a database using Office automation and creation of a single table where I show string, Boolean, number and data columns. There is a class that contains functions to learn if a table exists in an existing database, get all table names in a existing database and one for removal of an existing table. Lastly for demo purposes I have a class to assist with adding records to a table.

In the Windows form project I show how to use the methods above, create via automation or copy.

In closing you might think that what is shown may not be dynamic enough to things like the database and table names are fixed but this was done this way to make learning easier rather than complicate matters with code to ensure we don't overwrite an existing file or table to other naming schemes. The same holds true for how columns are created. Bottom line, I could have done the above but then the learning experience would be lost. A strong foundation is what I am after here.

How to search combobox items for a string and pick the containing combobox index

$
0
0
The ComboBox FindString and FindStringExact methods did not fulfill my needs.

The FindString was looking for a matching start of string so whatever string I passed had to be at the start. The FindStringExact method from what I read is suppose to look for a containing string (didn't have to be a complete string according to some stackoverflow posts).. but it didn't work.

I had a combobox with provinces and states for example "Ontario (ON)" or "Quebec (QC)" however my data was coming in only as "ON" or "QC" so I had to come up with my own solution:

vb Code:
  1. For i = 0 To RestProvinceState.Items.Count
  2.             If RestProvinceState.Items(i).ToString.Contains("(" & storeProvinceOrState & ")") Then RestProvinceState.SelectedIndex = i
  3.         Next

Now note that I didn't have to include the parentheses, however I wanted to reduce potential for error. For example the combobox item "Ontario (ON)" contains "on" twice, but what I really wanted to compare with was (ON).

Updating a control's screen area from a non-GUI thread.

$
0
0
At boops boops suggestion, I'm posting my first thread on this forum.
If you want to use a control's methods, and update its image through methods and events of the control, that work has to be done on the thread the Control was created, which is usually the GUI thread.
But, if you don't need to use the methods of the control, and you want to handle all the rendering of the screen area of the control yourself and are planning on doing so at a regular, quick rate as in animating a game so that you don't need to respond to the paint event, Microsoft has provided the BufferedGraphics object to allow for this. The following was my post in a thread about updating from a non-GUI thread. I've just copied and pasted that here.
...
You can use a BufferedGraphics object in any thread and draw into its buffer, then render that to the screen from that thread.
Microsoft provided that as a way to bypass the Windows GUI event processing overhead for programmers who want to have complete control over drawing to an area of the screen. The paint event processing with doublebuffered set is actually relatively slow at refreshing the screen from the backbuffer, limiting the update to around 128 hz, I believe.

An issue is that you can't refresh part of the screen area from the buffer like you can with the paint event by invalidating a rectangle. Of course you could have multiple bufferedGraphic objects to handle different parts of the screen, say an out the window view, a dashboard, mirror view, menus, etc.
Of course you could still have other areas that the gui thread still handled, if you wanted to use controls.

It is designed as a backbuffer frame that you do all your drawing on, then render the whole buffer to the screen area of a graphics object.
It is really meant for something that will be updating the screen regularly, like a game, so you don't need paint events because you are updating the whole area rapidly by design.

If you update rapidly in the GUI thread using the paint event, you can click and hold on the form's titlebar and you will notice the GUI thread stops for a short period, probably waiting to see if you're going to double-click or something.
If you update the screen area from the background thread, it keeps on running, so you don't get that pause.

Using a BufferedGraphics object is one of the few times that using CreateGraphics to get a graphics object is the correct thing to do.
Normally when you use GUI control from the GUI thread, then you would not use CreateGraphics, you would use the Graphics Object passed to you in the paint event.

I did part of a space invaders game as an experiment, and the GUI thread portion of the code was very short, just responding to the key inputs to the game.
The game loop ran in a background thread and did all the drawing for the game from that thread. Another background thread was responsible for playing the sounds of the game.
There was no drawing done in the GUI thread at all.

For a speed test, not the way the game would normally be run, I couldn't get paint events any faster than 128 hz, so the normal GUI thread method of updating was pretty much limited to that top speed. But using the background thread, I could update the screen thousands of times per second. Again, you wouldn't want to do that, but it is nice to have the bandwidth to do some extra drawing knowing that the refresh from backbuffer to screen would take very little time.

Anyway, a simple example where a panel's Graphics object (which would draw on the screen area "above" the panel) is passed to a BufferedGraphics object, so it can render to that area of the screen directly, bypassing the need to update that area in the GUI thread.
The background thread will just generate 400 random rectangles in the buffer, then render it to the screen area of the panel.
To show that it is the panel's area of the screen being updated by the BufferedGraphics object, you can click and drag on the panel to move it around while the background thread is rendering to it.

Create a new project. Add a panel to it, and make it a reasonable size, to fill a good portion of the form, but not docked, so you can move it around.
Paste in the code and run. Also drag on the panel.
Code:

Public Class Form1

  Dim thread1 As New Threading.Thread(AddressOf ThreadProc1)

  Dim appIsActive As Boolean = True
  Dim pnlHeight As Integer
  Dim pnlWidth As Integer

  Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    appIsActive = False
    Threading.Thread.Sleep(100) 'allow the thread to exit
  End Sub

  Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    pnlHeight = Panel1.ClientSize.Height
    pnlWidth = Panel1.ClientSize.Width
    thread1.IsBackground = True
    thread1.Start()
  End Sub

  Private Sub ThreadProc1()
    Dim g As Graphics = Panel1.CreateGraphics
    Dim rect As New Rectangle(0, 0, 100, 100)
    Dim sr As New Random
    Dim c As Color
    Dim br As New SolidBrush(Color.White)
    Dim gog As BufferedGraphics
    Dim goc As BufferedGraphicsContext = BufferedGraphicsManager.Current

    gog = goc.Allocate(g, New Rectangle(0, 0, pnlWidth, pnlHeight))
    Dim gb As Graphics = gog.Graphics

    Do While appIsActive
      For i As Integer = 0 To 399
        rect.X = sr.Next(pnlWidth)
        rect.Y = sr.Next(pnlHeight)
        rect.Width = sr.Next(5, 100)
        rect.Height = sr.Next(5, 100)
        c = Color.FromArgb(sr.Next(256), sr.Next(256), sr.Next(256))
        br.Color = c
        gb.FillRectangle(br, rect)
      Next
      gog.Render()
    Loop
    g.Dispose()
    br.Dispose()
  End Sub

  Private Sub Panel1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseMove
    Dim pnl As Panel = DirectCast(sender, Panel)
    Static lp As Point
    If e.Button = Windows.Forms.MouseButtons.Left Then
      pnl.Left += e.X - lp.X
      pnl.Top += e.Y - lp.Y
    Else
      lp = e.Location
    End If
  End Sub
End Class

BF Interpreter.NET - an interpreter for a minimalist programming language

$
0
0
BF Interpreter.NET is an interpreter for a minimalist programming language called Brain***** designed by Urban Müller. It only has eight different commands. The interpreter is a console program that can load and execute files containing source code for the language.

The code for a "Hello World!" program:
Code:

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
Wikipedia has more information, but due to the language's somewhat offensive name part of the url is censored by this forum so I can't post a direct link. Just search for "Urban Müller" and you should be able to find it.

An interpreter for Microsoft Visual Basic 6.0 can be found here:
http://www.vbforums.com/showthread.p...mming-language
Attached Files

[GUIDE] Syntax Highlighting in RichTextBox

$
0
0

RichTextBox Syntax Highlighting

Welcome to my guide on how to highlight syntax keywords such as: 'public, new, else, if, etc...'
First we will go through how to do it with VB.NET, I am currently using Visual Basic 2010 Express.


VB.NET Guide:

1. Open up VB and create a new project.
Name:  1.jpg
Views: 15
Size:  27.4 KB

2. Customize the form to whatever you desire.

3. Add a RichTextBox and set the properties so it looks professional.
Name:  2.jpg
Views: 14
Size:  28.2 KB

4.Now double click on the RichTextBox to get to the code event of RichTextBox.TextChanged

5. Now replace your current code with this:
Code:

Imports System.Text.RegularExpressions

Public Class Form1

    Private Sub RichTextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles RichTextBox1.TextChanged

Dim tokens As String = "(regex|dim|object|new|string|public|integer|end|auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while|1|2|3|4|5|6|7|8|9|my)"
        Dim rex As New Regex(tokens)
        Dim mc As MatchCollection = rex.Matches(RichTextBox1.Text)
        Dim StartCursorPosition As Integer = RichTextBox1.SelectionStart
        For Each m As Match In mc
            Dim startIndex As Integer = m.Index
            Dim StopIndex As Integer = m.Length
            RichTextBox1.[Select](startIndex, StopIndex)
            RichTextBox1.SelectionColor = Color.Blue
            RichTextBox1.SelectionStart = StartCursorPosition

            RichTextBox1.SelectionColor = Color.Black
        Next
    End Sub
End Class

-- Now lets go over the pieces of code individually.

Code:

Dim tokens As String = "(regex|dim|object|new|string|public|integer|end|auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while|1|2|3|4|5|6|7|8|9|my)"
^^^ This creates a new string with all of the keywords that will be highlighted.


Code:

        Dim rex As New Regex(tokens)
        Dim mc As MatchCollection = rex.Matches(RichTextBox1.Text)
        Dim StartCursorPosition As Integer = RichTextBox1.SelectionStart

^^^ This creates some variables that will be able to search for text in the RichTextBox later.


Code:

For Each m As Match In mc
            Dim startIndex As Integer = m.Index
            Dim StopIndex As Integer = m.Length
            RichTextBox1.[Select](startIndex, StopIndex)
            RichTextBox1.SelectionColor = Color.Blue
            RichTextBox1.SelectionStart = StartCursorPosition

            RichTextBox1.SelectionColor = Color.Black
        Next

^^^ This section sets up a 'For Statement' that will keep searching for the keywords defined in the string: 'tokens', and will hightlight them BLUE with the code:
Code:

RichTextBox1.SelectionColor = Color.Blue
and then set it back to BLACK with:
Code:

RichTextBox1.SelectionColor = Color.Black

[b]Thanks for reading! I hope I could help. If you need ANY help, don't hesitate to ask! :)

The C# Portion will be made later.


Created by MASON COOPER
Please give credit to me (by linking) if you decide to redistribute this guide!
Attached Images
  

Version Check

$
0
0
Something I came up with just now, I think some may find useful.

Basically place this in your program form load and if you want a button.

Checks local assembly version, checks a text file on server which holds the latest version. You can expand on this with a Yes/No or update button where the program closes and it runs the latest version setup.

vb Code:
  1. Shared Sub VersionCheck()
  2.         Try
  3.             Dim MyProgramVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString
  4.             Dim serverVersionFile As String = textfile-that-holds-version-on-server.txt
  5.             '
  6.             Dim reader As New System.IO.StreamReader(serverVersionFile, Encoding.Default)
  7.             Dim VersionFromFile
  8.             '            
  9.             Do While Not reader.EndOfStream
  10.                 VersionFromFile = reader.ReadLine
  11.             Loop
  12.             reader.Close()
  13.             '
  14.             Dim currentVersion As New Version(MyProgramVersion)
  15.             Dim serverVersion As New Version(VersionFromFile)
  16.             '
  17.             'Update somewhere in program labels for current and server version
  18.             MainWindow.OptionsLabelCurrentVersionResult.Text = currentVersion.ToString
  19.             MainWindow.OptionsLabelServerVersionResult.Text = serverVersion.ToString
  20.             'Throw messagebox with result
  21.             If Version.op_GreaterThan(serverVersion, currentVersion) Then
  22.                 MessageBox.Show("Current Version: " & MyProgramVersion & vbNewLine & "Server Version: " & serverVersion.ToString & vbNewLine & vbNewLine & "Please update to the latest version.", AppTitle)
  23.             End If
  24.         Catch ex As Exception
  25.             MessageBox.Show(ex.Message, AppTitle)
  26.         End Try
  27. End Sub

Adding a realtionship with an entity which is in the Deleted state is not allowed

$
0
0
I sometimes get the error message "Adding a relationship with an entity which is in the deleted state is not allowed" in my vb.net application at the line (BindSource.RemoveCurrent) that removes the current item from a binding source that its data source is the parent database table class which has
a parent/child relationship (1 to many) to other database table classes through foreign key. The deletion of parent table record is cascaded to the child tables. The classes and the relationship between the tables are mapped and handled by entity framework. The error consistently happens if prior item removed from the parent table has 1 to 0 relationship to this child table, and the current item being removed from the parent table has a 1 to 1 relationship to that same table. Any idea how to resolve this error?

Code:


            Do Until gridLogHeader.Rows.Count = 0
                gridLogHeader.CurrentCell = gridLogHeader.Rows(0).Cells(1)
 
                eLogForm.LogHeaderBindingSource.RemoveCurrent()    'Error message occurs at this line
            Loop
            Context.SaveChanges()

VideoLauncher Reborn - Play/Search Youtube videos

$
0
0
This is a simple app I made to watch, search and download videos from some video sites. It is written using vb.net and WPF. It also work with VEVO videos on Youtube that have a special signature protection :)

The app is incomplete, I don't made the downloader yet, multi-language support, skins and favorites are also missing (will be added soon) and not all sites works. Also, some small things needs to be fixed. I want opinions :D If you want to help with the project, just send me a PM and I will add on the github page.

Source here: https://github.com/gdkchan/VideoLauncher

I will release a more complete version very soon.

SNES.net - SNES emulator written in VB.NET

$
0
0
This is a simple SNES emulator I started last month, but I paused it for a while. It runs some games...

Tested working games (with bugs):
Super Mario World
Super Mario All-stars
Simpsons Barts Nightmare (major graphical issues)
Castlevania X (major graphical issues)
Mega Man X (X2 and X3 kind of work...)
Super Bomberman
Boogerman
Megaman 7
Street Fighter 2
Mario Paint
Final Fantasy 2
Contra III
Legend of Zelda - A link to the past
Krusty's Super Fun House

But the most awesome games like Chrono Trigger and some big RPGs doesn't work :cry::cry::cry:
The games that are not working are probably due to the lack of the SPC700 APU emulation. Actually, I already writted the code to emulate this APU, but I couldn't get it to work in sync with 65816 yet, so I don't pushed it to github.

Any help would be appreciated.
Source: https://github.com/gdkchan/SNES.net

About the speed: I remember on the beggining, the emulator ran Super Mario World at ~57 fps, almost fullspeed, but after I started to implement more stuff, it dropped to around ~35 fps (at least here) :( But I think I can optimize it to fullspeed again.
Viewing all 525 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>