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

How to get Microsoft Interop in toolbox for use

$
0
0
I'm trying to generate a VB interface with Excel, but the compiler does not recognize Imports Excel = Microsoft.Office.Interop.Excel and declares that Excel.Application does not exist.

Through some suggestions, from another post, I understood that the toolbox should have the Excel interop and I just needed to check it to include it in the project. No Excel, or office, shows up in the com library in the toolbox.

Is the toolbox where I want to do what I'm trying or is there another place that I would get the Excel Interop included in my project.

Much appreciate any help you can provide.

[RESOLVED] Modifying Excel workbooks, any good code available?

$
0
0
I am looking for some code that can allow me to manipulate an Excel book the way you can in VBA. I know the most common answer will be write it, but if there is some code available this would reduce the time needed for the VBA -> VB net conversion.

Anyone know where there may be a class or module that I can get for manipulating Excel from VB? I'm going to start trying to create a class, but as I mentioned it will be much easier not re-creating the wheel.

Thanks!

EDIT:
OK, starting out of the gate at not a good rate.

I generated the code below from some examples I could find, but mine just pukes and won't accept the same setup found on the web. Anyone see what is wrong? I'm sure there is some code that was in the example that was not shown, would be my luck.

Code:

Option Explicit On

Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop.Excel.Application
Imports Workbook = Microsoft.Office.Interop.Excel.Workbook  ,_ I added this.
Imports Worksheet = Microsoft.Office.Interop.Excel.Worksheet ,_ I added this.
Imports System.IO





Public Class ClsExcel

    Private m_szWBPath As String
    Private xlApp As Excel.Application <-Does not like

    'Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
    'Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet

    Public Function CreateExcelObject(ByVal szFileName As String) As Object

        m_szWBPath = Directory.GetCurrentDirectory()

        xlApp = New Excel.Application <- Does not like

what seems to be the issue?

[RESOLVED] function to capture keyboard events. Where do I find that?

$
0
0
I have a Form project with several combobox's on it. I need to catch the <ENTER> key.

How do I get the function generated, or do I need to create that myself?

EDIT: In VBA you could select the function of an item from a dropdown box and it would generate the code. Anything like this in VB Net?

[RESOLVED] How to get Microsoft Interop in toolbox for use

$
0
0
I'm trying to generate a VB interface with Excel, but the compiler does not recognize Imports Excel = Microsoft.Office.Interop.Excel and declares that Excel.Application does not exist.

Through some suggestions, from another post, I understood that the toolbox should have the Excel interop and I just needed to check it to include it in the project. No Excel, or office, shows up in the com library in the toolbox.

Is the toolbox where I want to do what I'm trying or is there another place that I would get the Excel Interop included in my project.

Much appreciate any help you can provide.

MouseHover same as MouseMove? How to get the x/y position of the window?

$
0
0
In VBA code the x/y parameters are sent with the call, so it's easy to do what I want with the item. (see below) I don't get a mousemove option from the tool, nor do I get x/y from e.

How would I get the x/y position of the mouse to determine if the cursor is on the object or not? I use the move over the object as a sign to extend the object for viewing hidden items in the GroupBox. Will the MouseHover do the same thing for me?

Code:

Private Sub FRM_REVIEW_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
   
    If (CurrentPhase = eRUN_MAIN_SECTION) Then
        FRM_INVESTIGATION_CONCLUSION.ZOrder (1)
        FRM_RISK.ZOrder (1)
        FRM_CAPA.ZOrder (1)
'        If (FRM_DHR.Height = 18) Then
            FRM_REVIEW.ZOrder (0)
'        End If

        FRM_REVIEW.SetFocus

        DoEvents
        If (X > 5 And X < 888 And Y < 320 And Y > -1) Then ' And FRM_REVIEW.Height < 338) Then
            FRM_RISK.Height = 18
            FRM_CAPA.Height = 18
            FRM_DHR.Height = 18
            FRM_REVIEW.Height = 336
        Else
            FRM_CAPA.Height = 18
            FRM_DHR.Height = 18
            FRM_RISK.Height = 18
            FRM_REVIEW.Height = 18
        End If
        DoEvents
    End If
   
End Sub

Thanks for the support.

Multiple Excel Interface questions

$
0
0
To reduce the number of threads I post regarding similar questions I'm posting them in 1 to hopefully make things less repeated.

This is a conversion from a VBA project.

First question:

I have defined xl as Worksheet, but I get the message that xl is not defined.
Code:

        Dim xl as Worksheet

Second Question:
I'm getting "Cells is not declared" when I have tried both Workbook and Worksheet, so I'm not sure why I'm getting this message.

Code:

                    xl.Range("C" & CStr(SB_SPIN3_MAIN.Value)).Select
                    szText = xl.Cells(SB_SPIN3_MAIN.Value, 3)

Third Question:
the following code gives me "Property Range is read only" for the range code.
Code:

Dim xl As Worksheet
Dim nRow As Integer
'    Dim nListIndex As Integer
Dim nCellCount As Integer

Try

    SelectExcelSheet(szTab)

    nCellCount = Excel.WorksheetFunction.CountA(Excel.Range(szCol & ":" & szCol))

    xl.Range(szCol & nCellCount + 1) = cb.Text

Any input is greatly appreciated.

[RESOLVED] calling a control from within the code to operate it

$
0
0
I'm trying to figure out how I would call a function within a function within VB Net. In VBA this is easy, but I have not figured out what arguments I would place into (e) in the function call.

Here is the VBA code, which is easy to call.
Code:

BTN_CREATE_TASK_Click()
Now in VB this is what the calling function looks like.
Code:

    Private Sub BTN_CREATE_TASK_Click(sender As Object, e As EventArgs) Handles BTN_CREATE_TASK.Click
What do I fill (e) will before I call the function, or do I need to call it another way say SendMessage?

VS 2022 Textmode=Time not displaying AM/PM

$
0
0
In my vb.net webforms application, I have a textbox with the Textmode = "Time". I need to show the correct AM/PM designation, so I am using the following code to populate the textbox:

txtTime.text = timeValue.ToString("hh:mm tt")

The timeValue in the database is "2025-03-23 17:00:00.000". When I use the "tt" parameter, nothing appears in the textbox.

If I use the following:

txtTime.text = timeValue.ToString("hh:mm") -- without the "tt" parameter

the textbox shows "05:00 AM", which is incorrect.

After adding a textbox labeled "txtTime" and setting TextMode=Time, I am running the following code which produces the results shown above:

Dim myTime As DateTime = "2025-03-23 17:00:00.000"
txtTime.Text = myTime.ToString("hh:mm tt")

Oddly enough, when debugging, the value shown in txtTime.Text is correct (05:00 PM)! However, the textbox does not show anything.

What am I missing???

VS 2012 Transaction problem (open datareader exception)

$
0
0
Hi, I want to insert data from one table to another. Using Transaction, I get an error message:
Quote:

ExecuteReader implies that the command has a transaction when the connection assigned to the command is in a pending local transaction. The command's Transaction property has not been initialized.
Code:

  Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        oleCon.Close()
        oleCon.Open()
        Dim strCategory As String = " SELECT Category.ID, Category.Label FROM Category WHERE Category.ID = 1 "
        Dim olecmd As New OleDbCommand(strCategory, oleCon)
        Dim trans As OleDbTransaction = oleCon.BeginTransaction
        Dim dreaderCategory As OleDbDataReader = olecmd.ExecuteReader
        Dim intID As Integer
        Dim strLabel As String = String.Empty
        While dreaderCategory.Read
            intID = dreaderCategory("ID")
            strLabel = dreaderCategory("Label")
        End While
        dreaderCategory.Close()
        Dim strCategory_2 As String = "INSERT INTO Category_2 (ID,Label) VALUES (@ID,@Label)"
        Dim olecomCategory_2 As New OleDbCommand(strCategory_2, oleCon)
        olecomCategory_2.Parameters.AddWithValue("@ID", intID)
        olecomCategory_2.Parameters.AddWithValue("@Label", strLabel)
        olecmd.Transaction = trans
        olecomCategory_2.ExecuteNonQuery()
        oleCon.Close()

        Dim strProduct As String = "SELECT Product.ID, Product.Label, Product.ID_Cat FROM Category, Product WHERE Product.ID_Cat = 1 "
        Dim intIDProduct As Integer
        Dim strLabelProduct As String
        Dim intID_CatProduct As Integer
        Dim olecmdProduct As New OleDbCommand(strProduct, oleCon)
        oleCon.Open()
        Dim dreaderProduct As OleDbDataReader = olecmdProduct.ExecuteReader
        While dreaderProduct.Read
            intIDProduct = dreaderProduct("ID")
            strLabelProduct = dreaderProduct("Label")
            intID_CatProduct = dreaderProduct("ID_Cat")
            Dim strProduct_2 As String = "INSERT INTO Product_2 (ID,Label,ID_Cat) VALUES (@ID,@Label,@ID_Cat)"
            Dim olecomProduct_2 As New OleDbCommand(strProduct_2, oleCon)
            olecomProduct_2.Parameters.AddWithValue("@ID", intIDProduct)
            olecomProduct_2.Parameters.AddWithValue("@Label", strLabelProduct)
            olecomProduct_2.Parameters.AddWithValue("@ID_Cat", intID_CatProduct)
            'olecomDetailCmd.Transaction = tran
            olecmd.Transaction = trans
            olecomProduct_2.ExecuteNonQuery()
        End While
        trans.Commit()
    End Sub

VS 2022 Application closes after displaying Crystal report several times

$
0
0
My first post in the community! I'm having a problem with my VB.NET application using Crystal Reports. I can run the same report seven or eight times in Crystal Reports, but at some point it closes without any error message. The same thing happens if I try to display it on screen or export it to PDF to view it with Acrobat. I don't think it's a Crystal runtime version issue. Any help is welcome. SAP CRystal Reports 13.0.37, same version runtime & developer version for VS.

Textbox.Lines.Count() not working

$
0
0
I'm trying to count the number of lines in a textbox, as the TB will change sizes based on the text insid of it. I have looked on the web and all examples give Textbox.Lines.Count as the answer.

When I try to do Textbox.lines there are no lines to select from the dropdown. What am I missing?

Code:

    Public Sub ResizeDescriptionTextbox(ByVal myTextBox As TextBox, Optional bExtend As Boolean = False)

        Dim nLineCnt As Integer

        If (Working = True) Then
            Exit Sub
        End If


        If (bExtend = True) Then
            'Get the number of lines the textbox has
            nLineCnt = myTextBox.Lines.count()    <- No dropdown to select lines to select count
            'Adjust the textbox to fit the size of the text to display
            myTextBox.Height = nLineCnt * cTBOX_LINE_HEIGHT_OFFSET
            'Adjust the frame height
            'myTextBox.Height = myTextBox.Height + nLineCnt + cFRAME_HEIGHT_OFFSET
            'Set the start position of the textbox to the begining
            myTextBox = 0

        Else
            myTextBox.Height = cTBOX_LINE_HEIGHT_DEFAULT
            TB_ANALYSIS.BringToFront()

        End If

    End Sub

Please enlighten me.

[RESOLVED] Textbox Vs Label - Same text, different outcomes

$
0
0
Ok, I'm guessing it's something that I'm stupidly missing.

Name:  textboxVsLabel.jpg
Views: 15
Size:  31.0 KB

Both the textbox which holds the Adventure Location ("G:\MyStuff\My Programs...."), and the label after "Intro for Adventure" should hold the same text ('adventuredir' holds a path to a textfile).

Code:

txtAdventureLoc.Text = adventuredir
lblAdventLoc.Text = adventuredir

But as you can see, the label cuts most of it off. Is there a setting in the label properties I need to change?
Attached Images
 

[RESOLVED] Textbox.Lines.Count() not working

$
0
0
I'm trying to count the number of lines in a textbox, as the TB will change sizes based on the text insid of it. I have looked on the web and all examples give Textbox.Lines.Count as the answer.

When I try to do Textbox.lines there are no lines to select from the dropdown. What am I missing?

Code:

    Public Sub ResizeDescriptionTextbox(ByVal myTextBox As TextBox, Optional bExtend As Boolean = False)

        Dim nLineCnt As Integer

        If (Working = True) Then
            Exit Sub
        End If


        If (bExtend = True) Then
            'Get the number of lines the textbox has
            nLineCnt = myTextBox.Lines.count()    <- No dropdown to select lines to select count
            'Adjust the textbox to fit the size of the text to display
            myTextBox.Height = nLineCnt * cTBOX_LINE_HEIGHT_OFFSET
            'Adjust the frame height
            'myTextBox.Height = myTextBox.Height + nLineCnt + cFRAME_HEIGHT_OFFSET
            'Set the start position of the textbox to the begining
            myTextBox = 0

        Else
            myTextBox.Height = cTBOX_LINE_HEIGHT_DEFAULT
            TB_ANALYSIS.BringToFront()

        End If

    End Sub

Please enlighten me.

Running a process with GUI from a Service

$
0
0
Hi guys,
I have a question.
I'm working on a Server Client app via UDP socket.
This is a 3 way program; Server, Client and Tray (originally written in .NET framework 4.8, and I'm upgrading them to .NET9, so I decided to re-write a few functions)
The Server is a Windows Form app that sits on a computer
The Client is a Windows Service.
The Tray is a window-less app that just has a Tray Icon, and can do a few things.

Situation:
The Client (service app) starts at Windows load (with a delay).
The Tray loads after a user logs in.
The old version (.NET 4.8) loaded the Tray with a Task Schedule entry that is triggered when a user logs in and when a user is unlocked.
New, in the new version (.NET9), I want the Client (service) to handle the Tray loading (because every time the user logs in or unlocks the computer there is a flash of blue window from the Powershell script).

Problem:
Since the Client is a service, it doesn't interact with the user interface (GUI).
I spent a lot of time with ChatGPT on this issue.
We managed to get the Tray app running, but there is no GUI aspect to it (the Tray Icon is not showing) and I can't interact with it.
What is going on here is the Client is running the Tray Process in the background and not in the user session, we tried to specify the session ID, and try to force it to run under the users GUI, but no luck.
Here is one of the codes we tried:
Code:

Imports System.Runtime.InteropServices
Public Class ProcessHelper
    ' Define STARTUPINFO structure
    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
    Public Structure STARTUPINFO
        Public cb As UInteger
        Public lpReserved As String
        Public lpDesktop As String
        Public lpTitle As String
        Public dwX As UInteger
        Public dwY As UInteger
        Public dwXSize As UInteger
        Public dwYSize As UInteger
        Public dwXCountChars As UInteger
        Public dwYCountChars As UInteger
        Public dwFillAttribute As UInteger
        Public dwFlags As UInteger
        Public wShowWindow As Short
        Public cbReserved2 As Short
        Public lpReserved2 As IntPtr
        Public hStdInput As IntPtr
        Public hStdOutput As IntPtr
        Public hStdError As IntPtr
    End Structure

    ' Define PROCESS_INFORMATION structure
    <StructLayout(LayoutKind.Sequential)>
    Public Structure PROCESS_INFORMATION
        Public hProcess As IntPtr
        Public hThread As IntPtr
        Public dwProcessId As UInteger
        Public dwThreadId As UInteger
    End Structure

    ' Define CreateProcess function from kernel32.dll
    <DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Public Shared Function CreateProcess(
        lpApplicationName As String,
        lpCommandLine As String,
        lpProcessAttributes As IntPtr,
        lpThreadAttributes As IntPtr,
        bInheritHandles As Boolean,
        dwCreationFlags As UInteger,
        lpEnvironment As IntPtr,
        lpCurrentDirectory As String,
        lpStartupInfo As STARTUPINFO,
        ByRef lpProcessInformation As PROCESS_INFORMATION) As Boolean
    End Function

    ' Method to get the last error code
    <DllImport("kernel32.dll", SetLastError:=True)>
    Public Shared Function GetLastError() As Integer
    End Function

    Public Shared Sub StartTray*****ingCreateProcess(trayAppPath As String)
        Dim startupInfo As New STARTUPINFO()
        startupInfo.cb = CUInt(Marshal.SizeOf(startupInfo))
        startupInfo.lpDesktop = "winsta0\default" ' Ensure running on the interactive desktop
        Dim processInfo As New PROCESS_INFORMATION()

        ' Start the process
        Dim result As Boolean = CreateProcess(trayAppPath, Nothing, IntPtr.Zero, IntPtr.Zero, False, 0, IntPtr.Zero, IO.Path.GetDirectoryName(trayAppPath), startupInfo, processInfo)

        If result Then
            CreateLog($"Started tray application (PID: {processInfo.dwProcessId})")
        Else
            Dim lastError As Integer = GetLastError()
            CreateLog($"Error starting tray application. Last Error: {lastError}")
        End If
    End Sub

    Private Shared Sub CreateLog(logMessage As String)
        Dim logFilePath As String = "D:\Logs\log.txt" ' Replace with your log file path
        Dim logEntry As String = $"{DateTime.Now}: {logMessage}"
        System.IO.File.AppendAllText(logFilePath, logEntry & Environment.NewLine & Environment.NewLine)
    End Sub
End Class

Here is another version:
Code:

Imports System
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports System.Text

Public Class ProcessHelper
    <DllImport("Wtsapi32.dll", SetLastError:=True)>
    Private Shared Function WTSQueryUserToken(sessionId As Integer, ByRef tokenHandle As IntPtr) As Boolean
    End Function

    <DllImport("Advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
    Private Shared Function DuplicateTokenEx(
        existingToken As IntPtr,
        desiredAccess As UInteger,
        tokenAttributes As IntPtr,
        impersonationLevel As Integer,
        tokenType As Integer,
        ByRef newToken As IntPtr) As Boolean
    End Function

    <DllImport("Kernel32.dll", SetLastError:=True)>
    Private Shared Function WTSGetActiveConsoleSessionId() As Integer
    End Function

    <DllImport("Userenv.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
    Private Shared Function CreateEnvironmentBlock(
        ByRef lpEnvironment As IntPtr,
        hToken As IntPtr,
        bInherit As Boolean) As Boolean
    End Function

    <DllImport("Userenv.dll", SetLastError:=True)>
    Private Shared Function DestroyEnvironmentBlock(lpEnvironment As IntPtr) As Boolean
    End Function

    <DllImport("Kernel32.dll", SetLastError:=True)>
    Private Shared Function CloseHandle(hObject As IntPtr) As Boolean
    End Function

    Public Shared Sub StartProcessAsUser(applicationPath As String)
        Dim sessionId As Integer = WTSGetActiveConsoleSessionId()
        If sessionId = 0 Then
            PCMonitor_Client.CreateLog("No active console session found.")
            Return
        End If

        Dim userToken As IntPtr = IntPtr.Zero
        Dim duplicateToken As IntPtr = IntPtr.Zero
        Dim environmentBlock As IntPtr = IntPtr.Zero

        Try
            ' Get user token for active session
            If Not WTSQueryUserToken(sessionId, userToken) Then
                PCMonitor_Client.CreateLog($"Failed to get user token. Error: {Marshal.GetLastWin32Error()}")
                Return
            End If

            ' Duplicate the token to create a primary token
            If Not DuplicateTokenEx(userToken, &H10000000UI, IntPtr.Zero, 2, 1, duplicateToken) Then
                PCMonitor_Client.CreateLog($"Failed to duplicate token. Error: {Marshal.GetLastWin32Error()}")
                Return
            End If

            ' Create environment block
            If Not CreateEnvironmentBlock(environmentBlock, duplicateToken, False) Then
                PCMonitor_Client.CreateLog($"Failed to create environment block. Error: {Marshal.GetLastWin32Error()}")
                environmentBlock = IntPtr.Zero ' Ensure it's null if creation fails
            End If

            ' Set process startup info
            Dim si As New ProcessStartInfo With {
                .FileName = applicationPath,
                .UseShellExecute = False,
                .RedirectStandardOutput = True,
                .RedirectStandardError = True,
                .CreateNoWindow = False,
                .WorkingDirectory = IO.Path.GetDirectoryName(applicationPath)
            }

            ' Set environment variables to ensure it runs on the correct desktop
            si.EnvironmentVariables("SESSIONNAME") = "Console"
            si.EnvironmentVariables("USERPROFILE") = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
            si.EnvironmentVariables("SystemRoot") = Environment.GetEnvironmentVariable("SystemRoot")
            si.EnvironmentVariables("TEMP") = Environment.GetEnvironmentVariable("TEMP")

            ' Set the desktop to the interactive user desktop (Winsta0\Default)
            si.EnvironmentVariables("USERDOMAIN") = Environment.UserDomainName

            ' Start process
            Using process As New Process()
                process.StartInfo = si
                process.Start()
                PCMonitor_Client.CreateLog($"Started {applicationPath} (PID: {process.Id}) for Session {sessionId}")

                ' Optional: Bring the window to the front (if needed)
                If process.MainWindowHandle <> IntPtr.Zero Then
                    SetForegroundWindow(process.MainWindowHandle)
                End If
            End Using

        Catch ex As Exception
            PCMonitor_Client.CreateLog($"Exception while starting process: {ex.Message}")
        Finally
            ' Clean up
            If environmentBlock <> IntPtr.Zero Then DestroyEnvironmentBlock(environmentBlock)
            If duplicateToken <> IntPtr.Zero Then CloseHandle(duplicateToken)
            If userToken <> IntPtr.Zero Then CloseHandle(userToken)
        End Try
    End Sub

    Public Shared Sub StartTrayAppInUserSession(applicationPath As String)
        Dim sessionId As Integer = WTSGetActiveConsoleSessionId()

        If sessionId = 0 Then
            PCMonitor_Client.CreateLog("No active console session found.")
            Return
        End If

        ' User token and environment setup
        Dim userToken As IntPtr = IntPtr.Zero
        Dim duplicateToken As IntPtr = IntPtr.Zero
        Dim environmentBlock As IntPtr = IntPtr.Zero

        Try
            ' Get user token for the active session
            If Not WTSQueryUserToken(sessionId, userToken) Then
                PCMonitor_Client.CreateLog($"Failed to get user token. Error: {Marshal.GetLastWin32Error()}")
                Return
            End If

            ' Duplicate the token to create a primary token
            If Not DuplicateTokenEx(userToken, &H10000000UI, IntPtr.Zero, 2, 1, duplicateToken) Then
                PCMonitor_Client.CreateLog($"Failed to duplicate token. Error: {Marshal.GetLastWin32Error()}")
                Return
            End If

            ' Create environment block
            If Not CreateEnvironmentBlock(environmentBlock, duplicateToken, False) Then
                PCMonitor_Client.CreateLog($"Failed to create environment block. Error: {Marshal.GetLastWin32Error()}")
                environmentBlock = IntPtr.Zero ' Ensure it's null if creation fails
            End If

            ' Set process startup info
            Dim si As New ProcessStartInfo With {
            .FileName = applicationPath,
            .UseShellExecute = False,
            .RedirectStandardOutput = True,
            .RedirectStandardError = True,
            .CreateNoWindow = False,
            .WorkingDirectory = IO.Path.GetDirectoryName(applicationPath)
        }

            ' Start process
            Using process As New Process()
                process.StartInfo = si
                process.Start()
                PCMonitor_Client.CreateLog($"Started {applicationPath} (PID: {process.Id}) for Session {sessionId}")

                ' Ensure tray application is brought to the front if necessary
                If process.MainWindowHandle <> IntPtr.Zero Then
                    SetForegroundWindow(process.MainWindowHandle)
                End If
            End Using

        Catch ex As Exception
            PCMonitor_Client.CreateLog($"Exception while starting tray app: {ex.Message}")
        Finally
            ' Clean up
            If environmentBlock <> IntPtr.Zero Then DestroyEnvironmentBlock(environmentBlock)
            If duplicateToken <> IntPtr.Zero Then CloseHandle(duplicateToken)
            If userToken <> IntPtr.Zero Then CloseHandle(userToken)
        End Try
    End Sub

    ' Add this method for bringing the window to the foreground (optional)
    <DllImport("user32.dll", SetLastError:=True)>
    Private Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean
    End Function
End Class

After a lot of tests, ChatGPT just goes in circles...
So I'm asking for help from the community.

Is there a way to load the Tray app from the Client (service) and get the GUI to work?

Thanks

[RESOLVED] Passing Combobox through prototype not working

$
0
0
I'm trying to pass a combobox through a prototype, not like last night where I was trying to access a textbox but was a combobox. The compiler does not like passing an object described like Combobox as a parameter through a function the way I am doing it (Not like VBA). See below

Caller
Value of type 'ComboBox' cannot be converted to 'VisualStyleElement.ComboBox'.
Code:

            LoadCBsectionNames(CB_NON_RETURNS_TEMPLATE, nTotalCount)
\


Function
Code:

    Public Function LoadCBsectionNames(ByVal varCombobox As ComboBox, ByVal nTotalCount As Integer) As Integer

        Dim ws As Worksheet
        Dim szCurCell As String
        Dim szLastCell As String
        Dim nCount As Integer

        szCurCell = ""
        szLastCell = ""
        'Look for all of the same items
        For nCount = 2 To nTotalCount

            szCurCell = ws.Range("A" + CStr(nCount)).Value2
            If (szCurCell <> szLastCell) Then
                '************* FIX ME **************
                varCombobox.items.add(szCurCell)
            End If
            szLastCell = szCurCell

        Next nCount

    End Function

Seems I need to add some other information when prototyping like this with a combobox. What would be the correct method to do so?


While I'm here...... The [Dim ws As Worksheet] is also providing an error. "Type 'Worksheet' is not defined."

Code:

Imports Excel = Microsoft.Office.Interop.Excel
Imports Workbook = Microsoft.Office.Interop.Excel.Workbook
Imports Worksheet = Microsoft.Office.Interop.Excel.Worksheet
Imports Worksheets = Microsoft.Office.Interop.Excel.Worksheets

I have tried to do
Code:

        Dim ws As Worksheet
        ws = new worksheet

any suggestions?? There is now light at the end of the tunnel with this VBA -> VB Net conversion.

[RESOLVED] Excel Interop warning code BC40056

$
0
0
Conversion from VBA to VB Net 2022. I'm getting a BC40056 warning message for the below Interop calls. I thought they were working as there was no RED so they were good to go. But I did see a faint line of GREEN and hovered over to get the BC40056 message. I have them referenced properly don't I?

What could the issue be? I'm not getting any of the imports to work and therefore, cannot make calls to Excel routines.


BC40056: Namespace or type specified in the Imports '<qualifiedelementname>' doesn't contain any public member or cannot be found

Code:

Imports Excel = Microsoft.Office.Interop.Excel
Imports Workbook = Microsoft.Office.Interop.Excel.Workbook
Imports Worksheet = Microsoft.Office.Interop.Excel.Worksheet
Imports Worksheets = Microsoft.Office.Interop.Excel.Worksheets

Here is an example of how I am trying to use them.

Code:

Public Shared Sub ExcelWriteErrorLog(ByVal szFunction, szMsg)

    Dim xcel As New Worksheet  <- Worksheet is in red and is not recognized.
    Dim varArray(0 To 3) As String
    Dim lRow As Integer

    Try

        varArray(0) = Format(Now, "mm/dd/yyyy")
        varArray(1) = Format(Now, "HH:mm:ss")
        varArray(2) = szFunction
        varArray(3) = szMsg

        If (Not gClsExcel Is Nothing) Then
            Exit Sub
        End If

        lRow = xcel.Range("A1").End(xlDown).Row
        xcel.Range("A" + CStr((lRow + 1))).Value2 = varArray(0)
        xcel.Range("B" + CStr((lRow + 1))).Value2 = varArray(1)
        xcel.Range("C" + CStr((lRow + 1))).Value2 = varArray(2)
        xcel.Range("D" + CStr((lRow + 1))).Value2 = varArray(3)

    Catch ex As Exception

    End Try

End Sub

Thanks for any assistance you can provide.

[RESOLVED] Excel Range reports as Read Only

$
0
0
I'm interfacing with Excel, and one line of code says that I can't write to it because it is "Read Only"?

I don't see why I can't write to the location, has it has not been defined yet by the x/y position, but I can't access this particular write instance. Anyone see a problem?

Code:

Public Function WriteIndexCellCB(ByVal cb As System.Windows.Forms.ComboBox, ByVal szTab As String, ByVal szCol As String)

    Dim ws As Excel.Worksheet

    Try

        'Delete the item index
        '    DeleteExcelColumnCB(szTab, szCol)
        ws.Range(szCol & cROW_START).Select()
        '***************** FIX ME ***************
        ws.Range(szCol & cROW_START) = cb.SelectedIndex        <-- Says read only

    Catch ex As Exception
        Dim szErr As String
        szErr = "Error occured for the following reason [" & ex.Message & "]"
        If (gClsEPIQ.GetIsDebug()) Then
            Debug.Print(szErr)
        End If
    End Try

End Function

Light at the end of the tunnel. Excel.Selection.end issue

$
0
0
I'm almost at the end, but one more issue that I'm fighting. I have tried Excel/Excel.workbook/Excel.worksheet/Excel.worksheets and none of these seem to work. What am I missing to make the "Selection" section of the code below happy?

This is moving over from VBa to VB Net, so not sure what the issue is. Is not an issue in VBA, but VB has different requirements so who knows?

Code:

    Public Sub SaveTab(ByVal strTab As String, ByVal varTab As Object)

        Dim ws As Excel.Worksheet
        Dim bStatus As Boolean

        Try

            If (gClsEPIQ.GetIsDebug()) Then
                Debug.Print("gClsEPIQ [SaveTabInfo Enter]")
            End If

            'Assume there will be no failure
            bStatus = False

            SelectExcelSheet(strTab)
            ws.Range("A2").End(xlDown).Select()
            '*************** FIX ME ****************
            'Set the items in the Settings tab
            ws.Range(Selection, Selection.End(xlDown)).CurrentRegion = varTab

        Catch ex As Exception
            Dim szErr As String
            szErr = "Error occured for the following reason [" & ex.Message & "]"
            If (gClsEPIQ.GetIsDebug()) Then
                Debug.Print(szErr)
            End If
            bStatus = True
        End Try

    End Sub

Thanks for your support.

VS 2022 How do I let the user create a folder?

$
0
0
How do I let the user of my app create a folder on disk? I want the user to be able to create a folder using a dialog box. I'll be then using that folder to create other folders within. So:


  1. User clicks 'Create Folder' button
  2. Dialog box opens
  3. User navigates to where they want the folder
  4. They create the folder using the dialog box.
  5. The app stores the path to the folder they have just created
  6. App adds folders into the folder the user just created.


I've searched online and know how to create a directory if I specify the path:

Code:

CreateDirectory("YourPath")
But I want the user to create the folder using a dialog box. I tried:

Code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    FolderBrowserDialog1.ShowDialog()
    Directory.CreateDirectory(FolderBrowserDialog1.SelectedPath & "\AFFCharacters")
End Sub

But that doesn't actually create the 'main' folder, just selects where to create the sub-folder "AFFCharacters". I want the user to be able to create a 'main' folder in which 'AFFCharacters' will automatically be created.

Hope that makes sense! And any help would be apprreciated. :)

I do not know what kind of symbols I have to put on my field ID

$
0
0
Hi guys, good morning. Does any one of you know about symbols? This message says my field ID is not closed. I suppose, and I think something is missing on the field ID.
Here is the Error. I can not figure out if someone knows. Can you help me, please?



Name:  Screenshot 2025-03-28 100614.jpg
Views: 39
Size:  45.0 KB
Attached Images
 
Viewing all 27489 articles
Browse latest View live


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