Модераторы: Akina
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Вызов API функций, синтокис со скобками и без них 
:(
    Опции темы
Гость_Archer
Дата 21.12.2005, 07:56 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











Не погу понять одной тонкости (если она вобще есть).
При вызове API функций для некоторых требуется синтаксис со скобками, для других без скобок:

s4.SetFieldValue_Articles ("Наименование", s_name) - вызывает ошибки
s4.SetFieldValue_Articles "Наименование", s_name - работает без проблем

хотя другие API функции того же объекта работают только со скобками:
designation = s4.GetFieldValue("Обозначение")

В чем тут фишка?
  Вверх
boevik
Дата 21.12.2005, 08:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник Клуба
Сообщений: 1452
Регистрация: 31.5.2004
Где: Израиль

Репутация: 12
Всего: 35



Если вызывается процедура (т.е. не определено возвращаемое значение), то вызов обязательно без скобок.
Если вызывается функция и при вызове присваивается возвращаемое значение какой либо переменной, то вызов обязательно со скобками.


--------------------
Никогда не говори никогда
PM MAIL WWW   Вверх
cardinal
Дата 21.12.2005, 17:01 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Инженер
****


Профиль
Группа: Экс. модератор
Сообщений: 6003
Регистрация: 26.3.2002
Где: Германия

Репутация: 19
Всего: 99



Цитата(MSDN)
Calling Procedures
The techniques for calling procedures vary, depending on the type of procedure, where it's located, and how it's used in your application. The following sections describe how to call Sub and Function procedures.

Calling Sub Procedures
A Sub procedure differs from a Function procedure in that a Sub procedure cannot be called by using its name within an expression. A call to a Sub is a stand-alone statement. Also, a Sub does not return a value in its name as does a function. However, like a Function, a Sub can modify the values of any variables passed to it.

There are two ways to call a Sub procedure:

' Both of these statements call a Sub named MyProc.
Call MyProc (FirstArgument, SecondArgument)
MyProc FirstArgument, SecondArgument

Note that when you use the Call syntax, arguments must be enclosed in parentheses. If you omit the Call keyword, you must also omit the parentheses around the arguments.

Calling Function Procedures
Usually, you call a function procedure you've written yourself the same way you call an intrinsic Visual Basic function like Abs; that is, by using its name in an expression:

' All of the following statements would call a function
' named ToDec.
Print 10 * ToDec
X = ToDec
If ToDec = 10 Then Debug.Print "Out of Range"
X = AnotherFunction(10 * ToDec)

It's also possible to call a function just like you would call a Sub procedure. The following statements both call the same function:

Call Year(Now)
Year Now

When you call a function this way, Visual Basic throws away the return value.

Calling Procedures in Other Modules
Public procedures in other modules can be called from anywhere in the project. You might need to specify the module that contains the procedure you're calling. The techniques for doing this vary, depending on whether the procedure is located in a form, class, or standard module.

Procedures in Forms
All calls from outside the form module must point to the form module containing the procedure. If a procedure named SomeSub is in a form module called Form1, then you can call the procedure in Form1 by using this statement:

Call Form1.SomeSub(arguments)

Procedures in Class Modules
Like calling a procedure in a form, calling a procedure in a class module requires that the call to the procedure be qualified with a variable that points to an instance of the class. For example, DemoClass is an instance of a class named Class1:

Dim DemoClass as New Class1
DemoClass.SomeSub

However, unlike a form, the class name cannot be used as the qualifier when referencing an instance of the class. The instance of the class must be first be declared as an object variable (in this case, DemoClass) and referenced by the variable name.

For More Information   You can find details on object variables and class modules in "Programming with Objects."

Procedures in Standard Modules
If a procedure name is unique, you don't need to include the module name in the call. A call from inside or outside the module will refer to that unique procedure. A procedure is unique if it appears only in one place.

If two or more modules contain a procedure with the same name, you may need to qualify it with the module name. A call to a common procedure from the same module runs the procedure in that module. For example, with a procedure named CommonName in Module1 and Module2, a call to CommonName from Module2 will run the CommonName procedure in Module2, not the CommonName procedure in Module1.

A call to a common procedure name from another module must specify the intended module. For example, if you want to call the CommonName procedure in Module2 from Module1, use:

Module2.CommonName(arguments)



--------------------
Немецкая оппозиция потребовала упростить натурализацию иммигрантов
В моем блоге: Разные истории из жизни в Германии

"Познание бесконечности требует бесконечного времени, а потому работай не работай - все едино".  А. и Б. Стругацкие
PM   Вверх
Fighter
Дата 22.12.2005, 22:24 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 810
Регистрация: 5.1.2005

Репутация: нет
Всего: 2



Код

Private Declare Function WinExec Lib "kernel32" (ByVal lpCmdLine As String, ByVal nCmdShow As Long) As Long
Dim a As Integer

Private Sub Command1_Click()
    a = WinExec("calc.exe", 0)
End Sub




Вот тебе кусок кода. Смотри и разбирайся.


Цитата(boevik @ 21.12.2005, 08:31)
Если вызывается процедура (т.е. не определено возвращаемое значение), то вызов обязательно без скобок.
Если вызывается функция и при вызове присваивается возвращаемое значение какой либо переменной, то вызов обязательно со скобками.


А так как WinAPI - это в основном функции, то апишки тебе наверное придется вызывать все время со скобками.
PM MAIL   Вверх
Exception
Дата 22.12.2005, 23:01 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник Клуба
Сообщений: 4525
Регистрация: 26.12.2004

Репутация: 7
Всего: 186



Если ты хочешь получить от ф-ции значение, скобки ставятся. Если значение не используется или это -- процедура, скобки опускаются. Вроде все :)
PM   Вверх
Fighter
Дата 23.12.2005, 01:06 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 810
Регистрация: 5.1.2005

Репутация: нет
Всего: 2



Цитата(Run @ 22.12.2005, 23:01)
Если ты хочешь получить от ф-ции значение, скобки ставятся. Если значение не используется или это -- процедура, скобки опускаются. Вроде все smile


А мне кажется, что если это процедура, то ты МОЖЕШЬ скобки ставить а МОЖЕШЬ НЕ СТАВИТЬ, а если функция, то тогда ты ДОЛЖЕН ставить скобки.
PM MAIL   Вверх
Exception
Дата 23.12.2005, 10:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник Клуба
Сообщений: 4525
Регистрация: 26.12.2004

Репутация: 7
Всего: 186



Цитата(Fighter @ 23.12.2005, 02:06)

А мне кажется

А ты проверь...
Код

Sub MySub(par As String)
End Sub
Function MyFunc(par As String) As Integer
MyFunc = 0
End Function
Sub Main
MySub "Тест"
Call MySub("Тест")
MyFunc "Тест"
Dim res As Integer
res = MyFunc("Тест")

Странный вопрос како-то smile
PM   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "VB6"
Akina

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Литературу по VB обсуждаем здесь
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь
  • Используйте теги [code=vb][/code] для подсветки кода. Используйтe чекбокс "транслит" (возле кнопок кодов) если у Вас нет русских шрифтов.


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Akina.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | VB6 | Следующая тема »


 




[ Время генерации скрипта: 0.0527 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.