Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Elnata COsta

entender este código VB.NET!

Recommended Posts

Então pessoal este é um código de um programa que interage com o jogo Flight Simulator X! Gostaria que vocês me ajudassem a entede-lo para que eu possa edita-lo! O código é o seguinte:

 

 

PS.: Há alguns comentários no código mas porém o que eu queria entender era algumas coisas do tipo:

 

   Dim com2bcd As Offset(Of Short) = New FSUIPC.Offset(Of Short)(&H3118) ' Example of reading a frequency coded in Binary Coded Decimal

 

No código acima como saber se irei colocar 'Of Integer', 'Of Byte', 'Of Double' etc! E como fazer para exibir estes valores por exemplo em uma textbox!

 

Imports FSUIPC
Imports System.Drawing.Drawing2D

Public Class CFP

    ' Constants
    Private Const AppTitle As String = "FSUIPCClientExample_VB"

    ' Register the Offsets we're interesing in for this application
    Dim horagame As Offset(Of Integer) = New FSUIPC.Offset(Of Integer)(&H238) 'HORA ATUAL DO JOGO
    Dim airSpeed As Offset(Of Integer) = New FSUIPC.Offset(Of Integer)(&H2BC) ' Basic integer read example
    Dim avionics As Offset(Of Integer) = New FSUIPC.Offset(Of Integer)(&H2E80) ' Basic integer read and write example
    Dim fsLocalDateTime As Offset(Of Byte()) = New FSUIPC.Offset(Of Byte())(&H238, 10) ' Example of reading an arbitary set of bytes.
    Dim aircraftType As Offset(Of String) = New FSUIPC.Offset(Of String)("AircraftInfo", &H3160, 24) ' Example of string and use of a group
    Dim lights As Offset(Of BitArray) = New FSUIPC.Offset(Of BitArray)(&HD0C, 2) ' Example of BitArray used to manage a bit field type offset.
    Dim compass As Offset(Of Double) = New FSUIPC.Offset(Of Double)(&H2CC) ' Example for disconnecting/reconnecting
    Dim pause As Offset(Of Short) = New FSUIPC.Offset(Of Short)(&H262, True) ' Example of a write only offset.
    Dim com2bcd As Offset(Of Short) = New FSUIPC.Offset(Of Short)(&H3118) ' Example of reading a frequency coded in Binary Coded Decimal
    Dim playerLatitude As Offset(Of Long) = New Offset(Of Long)(&H560) ' Offset for Lat/Lon features
    Dim playerLongitude As Offset(Of Long) = New Offset(Of Long)(&H568) ' Offset for Lat/Lon features
    Dim onGround As Offset(Of Short) = New Offset(Of Short)(&H366) ' Offset for Lat/Lon features
    Dim magVar As Offset(Of Short) = New Offset(Of Short)(&H2A0) ' Offset for Lat/Lon features
    Dim playerHeadingTrue As Offset(Of UInteger) = New Offset(Of UInteger)(&H580) ' Offset for moving the plane
    Dim playerAltitude As Offset(Of Long) = New Offset(Of Long)(&H570) ' Offset for moving the plane
    Dim slewMode As Offset(Of Short) = New Offset(Of Short)(&H5DC, True) ' Offset for moving the plane
    Dim sendControl As Offset(Of Integer) = New Offset(Of Integer)(&H3110, True) ' Offset for moving the plane
    Dim visibilidade As Offset(Of Integer) = New Offset(Of Integer)(&HF8C, True) ' Visibilidade
    Dim airspeedKnots As Double = (airSpeed.Value / 128D)





    ' Opens FSUIPC - if all goes well then starts the 
    ' timer to drive start the main application cycle.
    ' If can't open display the error message.
    Private Sub OpenFSUIPC()
        Try
            ' Attempt to open a connection to FSUIPC (running on any version of Flight Sim)
            FSUIPCConnection.Open()
            ' Opened OK so disable the Connect button
            Me.btnStart.Enabled = False
            Me.chkEnableAIRadar.Enabled = True
            ' and start the timer ticking to drive the rest of the application
            Me.Timer1.Interval = 200
            Me.Timer1.Enabled = True
            TextBox1.BackColor = Color.Green
            TextBox1.Text = "Connected"
            ' Set the AI object
            AI = FSUIPCConnection.AITrafficServices
        Catch ex As Exception
            ' Badness occurred - show the error message
            ' MessageBox.Show(ex.Message, AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error)
            MsgBox("Please start FSX/FS2004 or make sure you have FSUIPC installed!")
        End Try
    End Sub




 ' The timer handles the real-time updating of the Form.
    ' The default group (ie, no group specified) is 
    ' Processed and every Offset in the default group is updated.
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        Try

            ' Process the default group
            FSUIPCConnection.Process()

            ' IAS - Simple integer returned so just divide as per the 
            ' FSUIPC documentation for this offset and display the result.
            Dim airpeedKnots As Double = (airSpeed.Value / 128D)
            Me.txtIAS.Text = airpeedKnots.ToString("f1")


            ' Avionics Master Switch
            Me.chkAvionics.Checked = (avionics.Value > 0)  ' 0 = Off, 1 = On.


            ' Advanced Concept: Reading Raw Blocks of Data.
            ' FS Local Date and Time
            ' This demonstrates getting back an arbitrary number of bytes from an offset.
            ' Here we're getting 10 back from Offset 0x0328 which contain info about the 
            ' local date and time in FS.
            ' Because it's returned as a byte array we need to handle everything ourselves...
            ' 1. Year (starts at Byte 8) for 2 bytes. (Int16)
            '    Use the BitConverter class to get it into a native Int16 variable
            Dim year As Short = BitConverter.ToInt16(fsLocalDateTime.Value, 8)
            '    You could also do it manually if you know about such things...
            '    Dim year As Short = (fsLocalDateTime.Value(8) + (fsLocalDateTime.Value(9) * &H100))
            ' 2. Make new datetime with the the time value at 01/01 of the year...
            '    Time - in bytes 0,1 and 2. (Hour, Minute, Second):
            Dim fsTime As DateTime = New DateTime(year, 1, 1, fsLocalDateTime.Value(0), fsLocalDateTime.Value(1), fsLocalDateTime.Value(2))
            ' 3. Get the Day of the Year back (not given as Day and Month) 
            '    and add this on to the Jan 1 date we created above 
            '    to give the final date:
            Dim dayNo As Short = BitConverter.ToInt16(fsLocalDateTime.Value, 6)
            fsTime = fsTime.Add(New TimeSpan(dayNo - 1, 0, 0, 0))
            ' Now print it out
            Me.txtFSDateTime.Text = fsTime.ToString("dddd, MMMM dd yyyy hh:mm:ss")


            ' Lights
            ' This demonstrates using the BitArray type to handle
            ' a bit field type offset.  The lights are a 2 byte (16bit) bit field 
            ' starting in offset 0D0C.
            ' To make the code clearer and easier to write in the first
            ' place - I created a LightType Enum (bottom of this file).
            ' You could of course just use the literal values 0-9 if you prefer.
            ' For the first three, I've put alternative lines in comments
            ' that use a literal indexer instead of the enum.
            ' Update each checkbox according to the relevent bit in the BitArray...
            Me.chkBeacon.Checked = lights.Value(LightType.Beacon)
            'Me.chkBeacon.Checked = lights.Value(1)
            Me.chkCabin.Checked = lights.Value(LightType.Cabin)
            'Me.chkCabin.Checked = lights.Value(9)
            Me.chkInstuments.Checked = lights.Value(LightType.Instruments)
            'Me.chkInstuments.Checked = lights.Value(5)
            Me.chkLanding.Checked = lights.Value(LightType.Landing)
            Me.chkLogo.Checked = lights.Value(LightType.Logo)
            Me.chkNavigation.Checked = lights.Value(LightType.Navigation)
            Me.chkRecognition.Checked = lights.Value(LightType.Recognition)
            Me.chkStrobes.Checked = lights.Value(LightType.Strobes)
            Me.chkTaxi.Checked = lights.Value(LightType.Taxi)
            Me.chkWing.Checked = lights.Value(LightType.Wing)


            ' Compass heading
            ' Used to demonstrate disconnecting and reconnecting an Offset.
            ' We display the data in the field regardless of whether 
            ' it's been updated or not.
            Me.txtCompass.Text = compass.Value.ToString("F2")

            ' COM2 frequency
            ' Shows decoding a DCD frequency to a string
            ' a. Convert to a string in Hexadecimal format
            Dim com2String As String = com2bcd.Value.ToString("X")
            ' b. Add the assumed '1' and insert the decimal point
            com2String = "1" & com2String.Substring(0, 2) & "." & com2String.Substring(2, 2)
            Me.txtCOM2.Text = com2String


            ' VISIBILIDADE

            Dim visibilitySring As String = visibilidade.Value.ToString("X")
            visibilitySring = "1" & visibilitySring.Substring(0, 2) & "." & visibilitySring.Substring(2, 2)
            ' Me.VisibilitText.Text = visibilitySring


            ' Latitude and Longitude 
            ' Shows using the FsLongitude and FsLatitude classes to easily work with Lat/Lon
            ' Create new instances of FsLongitude and FsLatitude using the raw 8-Byte data from the FSUIPC Offsets
            Dim lon As FsLongitude = New FsLongitude(playerLongitude.Value)
            Dim lat As FsLatitude = New FsLatitude(playerLatitude.Value)
            ' Use the ToString() method to output in human readable form:
            ' (note that many other properties are avilable to get the Lat/Lon in different numerical formats)
            Me.txtLatitude.Text = lat.ToString()
            Me.txtLongitude.Text = lon.ToString()

            ' Using fsLonLatPoint to calculate distance and bearing between two points
            ' First get the point for the current plane position
            Dim currentPosition As FsLatLonPoint = New FsLatLonPoint(lat, lon)
            ' Get the distance between here and EGLL
            Dim distance As Double = 0
            Select Case (Me.cbxDistanceUnits.Text)
                Case "Nautical Miles"
                    distance = currentPosition.DistanceFromInNauticalMiles(EGLL)
                Case "Statute Miles"
                    distance = currentPosition.DistanceFromInFeet(EGLL) / 5280D
                Case "Kilometres"
                    distance = currentPosition.DistanceFromInMetres(EGLL) / 1000D
            End Select
            ' Write the distance to the text box formatting to 2 decimal places
            Me.txtDistance.Text = distance.ToString("N2")
            ' Get the bearing (True) 
            Dim bearing As Double = currentPosition.BearingTo(EGLL)
            ' Get the magnetic variation
            Dim variation As Double = magVar.Value * 360D / 65536D
            ' convert bearing to magnetic bearing by subtracting the magnetic variation
            bearing = bearing - variation
            ' Display the bearing in whole numbers and tag on a degree symbol
            Me.txtBearing.Text = bearing.ToString("F0") & Chr(&HB0)

            ' Now check if the player is on the runway:
            ' Test is the plane is on the ground and if the current position is in the bounds of
            ' the runway Quadrangle we calculated in the constructor above.
            Me.chkPlaneOnRunway.Checked = (Me.onGround.Value = 1 And runwayQuad.ContainsPoint(currentPosition))


        Catch exFSUIPC As FSUIPCException
            If exFSUIPC.FSUIPCErrorCode = FSUIPCError.FSUIPC_ERR_SENDMSG Then
                ' Send message error - connection to FSUIPC lost.
                ' Show message, disable the main timer loop and relight the 
                ' connection button:
                ' Also Close the broken connection.
                Me.Timer1.Enabled = False
                Me.AIRadarTimer.Enabled = False
                Me.btnStart.Enabled = True
                Me.chkEnableAIRadar.Enabled = False
                Me.chkEnableAIRadar.Checked = False
                FSUIPCConnection.Close()
                MessageBox.Show("The connection to Flight Sim has been lost.", AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                ' not the disonnect error so some other baddness occured.
                ' just rethrow to halt the application
                Throw exFSUIPC
            End If

        Catch ex As Exception
            ' Sometime when the connection is lost, bad data gets returned 
            ' and causes problems with some of the other lines.  
            ' This catch block just makes sure the user doesn't see any
            ' other Exceptions apart from FSUIPCExceptions.
        End Try
    End Sub





 ' Demonstrates the Grouping facility and also returning a string.
    ' The AircraftType Offset is in a Group called "AircraftInfo".
    ' With the Group system you can gain control over which 
    ' Offsets are processed.
    Private Sub btnGetAircraftType_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetAircraftType.Click
        ' Aircraft type is in the "AircraftInfo" data group so we only want to proccess that here.
        Try
            FSUIPCConnection.Process("AircraftInfo")
            ' OK so display the string
            ' With strings the DLL automatically handles the 
            ' ASCII/Unicode conversion and deals with the 
            ' zero terminators.
            Me.txtAircraftType.Text = aircraftType.Value
        Catch ex As Exception
            MessageBox.Show(ex.Message, AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

 

Desculpe-me mais sou leigo no assunto VB.NET, estou migrando para essa área agora minha área mesmo é desenvolvimento web

!

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

É um complemento para game, utiliza o sistema de drawing2D, eu não estou entendendo porque uma pessoa que está começando agora já pega algo tão complicado deste tipo, mas tudo bem, qual é a alteração que você quer fazer?

Compartilhar este post


Link para o post
Compartilhar em outros sites

É um complemento para game, utiliza o sistema de drawing2D, eu não estou entendendo porque uma pessoa que está começando agora já pega algo tão complicado deste tipo, mas tudo bem, qual é a alteração que você quer fazer?

Olá KhaosDoctor! Bom primeiramente sei que não estou certo de estar querendo pegar algo tão complicado como esse! Porém eu achei muito interessante este sistema! Estou querendo desenvolver um software que administra o site (empresa) e acima de tudo trabalhe juntamente com o Game FSX! Com a sua ajuda aqui no fórum consegui resolver a parte de administração e login! Porém nesta parte ai já não consegui mais entender o sistema (e vi que realmente ainda tenho que aprender muito.)! E a alteração que eu gostaria de fazer é a seguinte:

 

Por exemplo tenho a seguinte linha de comando:

 

 

  Dim com2bcd As Offset(Of Short) = New FSUIPC.Offset(Of Short)(&H3118) ' Exemplo de leitura de uma freqüência codificado em Binary Coded Decimal

 

Então gostaria de fazer o seguinte em uma textbox1 iria exibir a frequência atual do com2 e na textbox2 iria ser para colocar a nova frequência com2 e button que seria pra atualizar a frequência no game!

 

Essa seria uma atualização que eu gostaria de fazer!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Para exibir você pega a caixa de texto e exibe o valor, sem segredos:

 

Texbox1.Text = com2bcd.ToString

 

Para setar o valor:

 

com2bcd = New FSUIPC.Offset(Of Short)(Valor)

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.