Muchas gracias xskyx por el código, si funciona correctamente en windows 10 1909.
Saludos.
Saludos.
Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.
Mostrar Mensajes MenúCita de: Loretz en 9 Abril 2020, 05:11 AM
Puedes hacer algo como esto, pero ten en cuenta que en C++ no debes usar punteros, no debes usar new (ni delete).#include <iostream> // para cout
#include <cstring> // para strncpy
int NombreFuncion(char* Dato, size_t &BufferDato) {
const char* texto = "resultado";
if (BufferDato < strlen(texto)+1) {
BufferDato = strlen(texto) +1;
return 0; // texto es más largo que BufferDato
}
strncpy(Dato, texto, BufferDato);
Dato[BufferDato-1] = '\0';
return 1;
}
int main()
{
size_t size = 1;
char* dato = new char[size];
if (NombreFuncion(dato, size))
std::cout << "dato = " << dato << '\n';
else
std::cout << "dato debe ser al menos de " << size << " bytes\n";
delete[] dato;
}
Gracias Loretz, hice correr el código en dev c++ y todo ok, y tambien probé en el IDE de visual studio 2015 y me salta el error al compilar en la siguiente linea
...
strncpy(Dato, texto, BufferDato);
...
El error que se muestra es lo siguienteError C4996 'strncpy': This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
Generalmente yo uso el IDE de visual studio 2015, alguna librería debo incluir?
tambien probé con strncpy_s y nada me dice ninguna sobrecarga coincide para la función.
Una vez mas gracias por tu respuesta estimado:
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, ByRef nSize As Long) As Long
int NombreFuncion(char* Dato, int &BufferDato) {
char* texto = "resultado";
Dato = texto;//BufferDato para ver la cantidad de caracteres para el texto
return 1;
}
ListView2.SelectedItems(0).EnsureVisible()
Private Const EWX_LOGOFF As Integer = 0
Private Const EWX_SHUTDOWN As Integer = 1
Private Const EWX_REBOOT As Integer = 2
Private Const EWX_FORCE As Integer = 4
Private Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
Private Const TOKEN_QUERY As Integer = &H8
Private Const SE_PRIVILEGE_ENABLED As Integer = &H2
Private Const ANYSIZE_ARRAY As Integer = 1
Private Const VER_PLATFORM_WIN32_NT As Integer = 2
Private Structure OSVERSIONINFO
Dim dwOSVersionInfoSize As Integer
Dim dwMajorVersion As Integer
Dim dwMinorVersion As Integer
Dim dwBuildNumber As Integer
Dim dwPlatformId As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=128)> Dim szCSDVersion As String
End Structure
Private Structure LUID
Dim LowPart As Integer
Dim HighPart As Integer
End Structure
Private Structure LUID_AND_ATTRIBUTES
Dim pLuid As LUID
Dim Attributes As Integer
End Structure
Private Structure TOKEN_PRIVILEGES
Dim PrivilegeCount As Integer
Dim laa As LUID_AND_ATTRIBUTES
End Structure
Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As IntPtr, ByVal DesiredAccess As IntPtr, ByRef TokenHandle As IntPtr) As Integer
Private Declare Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LUID) As Integer
Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Int32, ByVal dwReserved As Int32) As Int32
<DllImport("advapi32.dll", SetLastError:=True)> Private Function AdjustTokenPrivileges(ByVal TokenHandle As IntPtr, ByVal DisableAllPrivileges As Boolean, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLengthInBytes As Integer, ByRef PreviousState As TOKEN_PRIVILEGES, ByRef ReturnLengthInBytes As Integer) As Boolean
End Function
<DllImport("Kernel32.dll")> Private Function GetVersionEx(<MarshalAs(UnmanagedType.Struct)> ByRef osinfo As OSVERSIONINFO) As Integer
End Function
Private Sub EnableShutDown()
Dim hProc As IntPtr, hToken As IntPtr, mLUID As LUID, mPriv As TOKEN_PRIVILEGES, mNewPriv As TOKEN_PRIVILEGES
hProc = Process.GetCurrentProcess.Handle
OpenProcessToken(hProc, TOKEN_ADJUST_PRIVILEGES + TOKEN_QUERY, hToken)
LookupPrivilegeValue("", "SeShutdownPrivilege", mLUID)
mPriv.PrivilegeCount = 1
mPriv.laa.pLuid = mLUID
mPriv.laa.Attributes = SE_PRIVILEGE_ENABLED
Call AdjustTokenPrivileges(hToken, False, mPriv, 4 + (12 * mPriv.PrivilegeCount), mNewPriv, 4 + (12 * mNewPriv.PrivilegeCount))
End Sub
' para apagar windows, este codigo hace sin importar el tipo de usuario este en ese momento igual lo apagara si Forzar es True le obliga a apagar
'como se puede obtener similar permiso para copiar el archivo en un windows que pertenece a un dominio?
Public Sub ApagarWindows(ByVal Optional Forzar As Boolean = True)
Dim Flags As Integer = EWX_SHUTDOWN
If Forzar Then Flags = Flags + EWX_FORCE
EnableShutDown()
ExitWindowsEx(Flags, 0)
End Sub
LookupPrivilegeValue("", "SeShutdownPrivilege", mLUID)
LookupPrivilegeValue("", "SeRestorePrivilege", mLUID)
Imports System.Data.SqlClient
Imports System.Threading
Imports System.ComponentModel
<Microsoft.VisualBasic.ComClass()> <ToolboxBitmap(GetType(System.Windows.Forms.ListView))> <System.Serializable()> Public Class ListView
Inherits Windows.Forms.ListView
Dim thSQL As Thread
Dim _sq As String, _decimales As Integer, _EllipseIcon As Boolean, _bordColor As Pen
Public Sub SQLConsulta(ByVal sq As String, Optional ByVal EllipseIcon As Boolean = False, Optional ByVal borderColor As Pen = Nothing, Optional ByVal decimales As Integer = 0)
_sq = sq : _decimales = decimales : _EllipseIcon = EllipseIcon : _bordColor = borderColor
thSQL = New Thread(AddressOf SQLConsultaInterno)
thSQL.Start()
End Sub
Private Sub SQLConsultaInterno()
Try
Dim h As Thread
Dim conexion As SqlConnection = New SqlConnection()
conexion.ConnectionString = "Data Source=ip_server,1433;Failover Partner=ip_server2,1433;Network Library=DBMSSOCN;MultipleActiveResultSets=true;Initial Catalog=DB;User ID=sa;Password=contraseña;" : conexion.Open()
Dim ds As New DataSet(), da As New SqlDataAdapter(_sq, conexion) : da.Fill(ds, "tabla")
If ds.Tables("tabla").Columns.Count = 1 Then
For c As Integer = 0 To ds.Tables("tabla").Columns.Count - 1
AddColumn(ds.Tables("tabla").Columns(c).Caption)
Next
Else
For c As Integer = 1 To ds.Tables("tabla").Columns.Count - 1
AddColumn(ds.Tables("tabla").Columns(c).Caption)
Next
End If
With ds.Tables("tabla")
For filas As Integer = 0 To .Rows.Count - 1
Dim ob As New ROW
ob.fila = .Rows(filas)
ob.columnas = .Columns.Count
ob.index = filas
h = New Thread(AddressOf agregar)
h.Start(ob)
Next
End With
conexion.Close()
Catch ex As Exception
End Try
End Sub
Private Sub agregar(obj As Object)
Dim rw As ROW = DirectCast(obj, ROW)
If rw.columnas = 1 Then
Dim Registro As New ListViewItem(rw.fila.Item(0).ToString.Trim, rw.index)
AddItem(Registro)
Else
Dim Registro As New ListViewItem(rw.fila.Item(1).ToString.Trim, rw.index)
Registro.Tag = rw.fila.Item(0).ToString.Trim
For c As Integer = 2 To rw.columnas - 1
Registro.SubItems.Add(rw.fila.Item(c).ToString().Trim)
Next
AddItem(Registro)
End If
End Sub
Delegate Sub AddColumns(ByVal texto As String)
Private Sub AddColumn(ByVal texto As String)
If Me.InvokeRequired Then
Dim d As New AddColumns(AddressOf AddColumn)
Invoke(d, New Object() {texto})
Else
Me.Columns.Add(texto)
End If
End Sub
Delegate Sub AddItems(ByVal item As ListViewItem)
Private Sub AddItem(ByVal item As ListViewItem)
If Me.InvokeRequired Then
Dim d As New AddItems(AddressOf AddItem)
Invoke(d, New Object() {item})
Else
Me.Items.Add(item)
End If
End Sub
Private Class ROW
Property fila As DataRow
Property columnas As Integer
Property index As Integer
End Class
End Class
Imports System.Runtime.InteropServices
Friend Class HeaderControl
Inherits NativeWindow
<DllImport("user32.dll", EntryPoint:="SendMessage")>
Private Shared Function SendMessage(hwnd As IntPtr, wMsg As Integer, wParam As IntPtr, lParam As IntPtr) As IntPtr
End Function
Private Const LVM_GETHEADER As UInt32 = &H101F
Private Const WM_MOUSEMOVE As Int32 = &H200
Public Sub New(LV As ListView)
'Get handle to LV header
Dim hWnd_LV_Header As IntPtr = SendMessage(LV.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero)
If hWnd_LV_Header <> IntPtr.Zero Then
Me.AssignHandle(hWnd_LV_Header)
AddHandler LV.HandleDestroyed, AddressOf LV_destroy ' To release handle when LV destroyed?
End If
End Sub
Private Sub LV_destroy(sender As Object, e As EventArgs)
Me.ReleaseHandle()
End Sub
' subclass LV header...
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
Select Case m.Msg
Case WM_MOUSEMOVE ' https://msdn.microsoft.com/en-us/library/windows/desktop/ms645616%28v=vs.85%29.aspx
' show mouse location over LV column header
Debug.WriteLine("x={0}, y={1}", m.LParam.ToInt32 And &HFFFF&, m.LParam.ToInt32 \ &H10000 And &HFFFF&) ' http://support.microsoft.com/kb/112651
End Select
MyBase.WndProc(m)
End Sub
End Class
Public Class ListView
Inherits Windows.Forms.ListView
Public Sub New()
'
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
'mensajes de listview
MyBase.WndProc(m)
End Sub
End Class