NikRock NikRock - 5 months ago 10
Vb.net Question

How to access a function from an outside class in VB.NET

I'm trying to access a function which belongs to a Class frmamain from another class. please can anyone tell me how i have to achieve this? i'm new to VB.NET. thanks in advance.

The code throws the following error

"ConvertImagerBnW() is not declared. it may be inaccessible due to its protection level"

class frmamain
Public Function ConvertImagerBnW()

Try
Dim img As Bitmap = New Bitmap((Image.FromFile("D:\\imgnam.jpg")))
''Dim img As Bitmap = New Bitmap(ImageBox1.Image)
Dim c As Color
Dim i As Integer = 0
Do While (i < img.Width)
Dim j As Integer = 0
Do While (j < img.Height)
c = img.GetPixel(i, j)
Dim r As Integer = 0
r = Convert.ToInt16(c.R)
Dim g As Integer = 0
g = Convert.ToInt16(c.G)
Dim b As Integer = 0
b = Convert.ToInt16(c.B)
Dim ans As Integer = ((r _
+ (g + b)) _
/ 3)
If (ans > 128) Then
r = 255
g = 255
b = 255
Else
r = 0
g = 0
b = 0
End If
c = Color.FromArgb(r, g, b)
img.SetPixel(i, j, c)
j = (j + 1)
Loop
i = (i + 1)
Loop
''Image<Gray, Byte> normalizedimg = new Image<Gray, Byte>(img);
img.Save("D:\\imgnamNew.jpg")
Dim Bmp1 As New Image(Of Bgr, [Byte])("D:\\imgnamNew.jpg")
ImageFrame = Bmp1
''ImageBox1.Image = ImageFrame
''ImageBox1.Image.Save("D:\\imgnamNew.jpg")
'' MessageBox.Show("SUCESSFULLY DONE")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

End Function
end class


Module UseThread
Sub newthread()
ConvertImagerBnW()
End Sub
End Module

Answer

ConvertImagerBnW is a member of the frmamain class so you have to actually call it on an instance of that class. This:

Module UseThread
    Sub newthread()
      ConvertImagerBnW()
    End Sub
End Module

doesn't know anything about frmamain. At it's simplest, you need to do something like this:

Module UseThread
    Sub newthread()
      frmamain.ConvertImagerBnW()
    End Sub
End Module

That will call that method on the default instance of frmamain, assuming that it's a form. If it's not the default instance or it's not a form then you need to access an instance form somewhere. That might look like this:

Module UseThread
    Sub newthread()
      Dim obj As New frmamain

      obj.ConvertImagerBnW()
    End Sub
End Module

If you want to call the method on an existing instance rather than a new instance then you'd have to get a reference to that instance from somewhere. Exactly how you would do that depends on the specifics of your project.